blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
104348393865407f385ae16aa8295747ae711746
Aasthaengg/IBMdataset
/Python_codes/p02379/s453645124.py
149
3.671875
4
#ITP1_10-A Distance x1,y1,x2,y2 = input().split(" ") x1=float(x1) y1=float(y1) x2=float(x2) y2=float(y2) print ( ((x1-x2)**2.0 + (y1-y2)**2.0 )**0.5)
abddade25f89b83a28dd56a92f742a6ef0e3e04f
zacharyzhu2023/CS61C
/lectures/Lec31-IO Devices.py
6,193
4.03125
4
Lecture 31: I/O Devices I/O Devices - I/O interface provides mechanism for program on CPU to interact w/ outside world - Examples of I/O devices: keyboards, network, mouse, display - Functionality: connect many devices--control, respond, & transfer data b/w devices - User programs should be able to build on their functionality - Tasks of processor for IO: input (read bytes), output (write bytes) - Can either use: special I/O instructions/hardware OR memory mapped I/O - Special instructions/hardware inefficient b/c constantly have to change as hardware changes - Memory mapped I/O: allocate address space for IO, which contain IO device registers - Addresses 0x7FFFFFFF and below are reserved for memory mapped IO - Each IO device has a copy of its control reg & data reg in region of memory-mapped IO - 1GHz IO throughput: 4 GiB/s (for load/store word operations) - I/O data rates: 10 B/s (keyboard), 3 MiB/s for bluetooth, 64 GiB/s (HBM2 DRAM) I/O Polling - Device registers have 2 functions: control reg (gives go-ahead for R/W operations) & data reg (contains data) - Polling: Processor reads from control reg in loop: if control reg readyBit = 1 --> data is available or ready to accept data. Then, load data from input or write output to data reg. Last, reset control reg bit to 0 Memory map: Input control reg-0x7ffff000, Input data reg-0x7ffff004, Output control reg-0x7ffff008, Output data reg-0x7ffff00c INPUT: read into a0 from IO Device lui t0, 0x7ffff # IO Address: 7fffff000 wait: lw t1, 0(t0) # Read the control andi t1, t1, 0x1 # Check the ready bit of control beq t1, x0, wait # Keep waiting if ready bit != 1 lw a0, 4(t0) # Once we have valid ready bit, load input data reg OUTPUT: write to display from a1 lui t0, 0x7ffff # Same address as above wait: lw t1, 0(t0) # REad the control andi t1, t1, 0x1 # Check ready bit of control beq t1, x0, wait # Keep waiting if ready bit != 1 sw a1, 12(t0) # Store output data from a1 - Assume processor has specifications: 1 GHz clock rate, 400 clock cycles per polling operation - % Processor for polling = Poll Rate * Clock cycles per poll/Clock Rate - Example: mouse that conducts 30 polls/s --> % Processor for Polling = 30 * 400/(10^9) = 0.0012% I/O Interrupts - Idea: polling is wasteful of finite resources b/c constantly waiting for an event to occur - Not a great idea when dealing with large quantities of input/output data - Alternative: interrupt which "interrupts" the current program and transfers control to trap handler when I/O is ready to be dealth with - Throw an interrupt when delivering data or need have relevant information - No IO activity? Regular program continues. Lots of IO? Interrupts are expensive b/c caches/VM are garbage, requiring saving/restoring state often - Devices w/ low data rate (ex: mouse, keyboard): use interrupts (overhead of interrupt is low) - Devices w/ high data rate (ex: network, disk): start w/ interrupt then switch to direct memory access (DMA) - Programmed I/O: used for ATA hard drive which has processor that initiates all load/store instructions for data movement b/w device. CPU obtains data from device and delivers it to main mem & also performs computation on that data - Disadvantages: CPU in charge of transfers (better spent doing smth else), device & CPU speeds misaligned, high energy cost of using CPU when alternative methods exist Direct Memory Access (DMA) - DMA allows IO devices to read/write directly to main memory, utilizing DMA Engine (piece of hardware) - DMA engine intended to move large chunks of data to/from data, working independently - DMA engine registers contain: mem addr for data, num bytes, I/O device num, direction of transfer, unit of transfer, amount to transfer - Steps for the DMA transfer: Step 1: CPU intiaites transfer (writing addr, count, and control into DMA controller) Step 2: DMA requests transfer to memory (goes through the disk controller, which contains a buffer) Step 3: Data gets transferred to main memory from the disk controller (through its buffer) Step 4: Disk controller send an acknowledgement back to the DMA controller Step 5: Interrupt the CPU when all the above operations are completed - CPU interrupted twice: once to start the transfer (meanwhile, CPU can do whatever else), and then at the end to indicate that the transfer is complete - Procedure DMA uses for dealing w/ incoming data: receive interrupt from device, CPU takes interrupt/start transfer (place data at right address), device/DMA engine handles transfer, Device/DMA Engine interrupts CPU to show completion - Procedure for outgoing data: CPU initiates transfer/confirms external device ready, CPU initiates transfer, Device/DMA engine handles transfer, Device/DMA engine interrupts CPU to indicate completion - DMA Engine can exist b/w L1$ and CPU: which allows for free coherency but trashes CPU working set for the data transferred - Free coherency: processor memory/cache system is going to have coherency - Can also exist b/w last level cache and main memory: does not mess w/ caches but need to manage coherency explicitly Networking - I/O devices can be shared b/w computers (ex: printers), communicate b/w computers (file transfer protocol-FTP), communicate b/w ppl (ex: email), communicate b/w computer networks (ex: www, file sharing) - Internet conceptualized in 1963 when JCR Licklider writes about connecting computers b/w universities - 1969: 4 nodes deployed at colleges, 1973: TCP invented, part of internet protocol suite - World Wide Web: system of interlinked hypertext documents on the internet - 1989: Sir Tim Berners Lee develops Hypertext Transfer Protocol (HTTP) allowing for client & server for the internet - Software protocol to send/receive: 1. SW SEND: copy data to OPS buffer, calculate checksum w/ timer, send data to network interface hardware to start 2. SW RECEIVE: OS copies data from network interface hardware to OS buffer, OS calculates checksum--if fine, send ACK, else delete msg If fine, copy data into user address space & tell application it can continue - Requires a network interface card (NIC) that can be wired or wireless
0cdc20f67a4f0e5b45ce1ea494b24bed2b3bfbb5
min0201ji/PythonStudy
/Ch03/for/for_ex3.py
301
3.796875
4
# 카운트 다운 프로그램 x = int(input('시작 숫자를 입력하시오: ')) for a in range(x,0,-1): print(a,end=' ') print('발사!') # # 선생님 답 # count = int(input('시작 숫자를 입력하시오: ')) # # for x in range(count, 0,-1): # print(x,end=' ') # print('발사!')
abefd5d55e3b05b0281d539c3cb2aea88f3e473c
Artemka225/Morskoy-boy-
/untitled12/ain.py
1,369
3.71875
4
def ships_add(n): print("Расположите ваши корабли") for i in range(1, 5): n=ships_info(n, i) return n def ships_info(n, lenship): z1 = list(map(int, input("Выберите где будет распологаться первая клетка"+ lenship +"- х палубного корабля").split())) z2 = list(map(int, input("Выберите где будет распологаться последняя клетка"+ lenship+"- х палубного корабля").split())) print(z1, z2) if (z2[0] - z1[0] == lenship-1): for i in range(z1[0] - 1, z2[0]): n[z1[1]][i] = 1 elif (z2[1] - z1[1] == lenship-1): for i in range(z1[1] - 1, z2[1]): n[i][z1[1]] = 1 else: print("ведены не корректные значения") return n def print_plase(n): for i in range(10): print(n[i]) def frame_ships(n, z1, z2): if (z1[0]-1>0)and(z1[0]+1<11): if (z1[1]-1>0)and(z1[1]+1<11): for i in range(z1[0]-2,z2[0]+1): n[i][z1[1]]=0 for i in range() def main(): n=[[[] for i in range(10)] for j in range(10)] m=[[[] for i in range(10)] for j in range(10)] print_plase(n) print_plase(m) n=ships_add(n) print_plase(n) if __name__=='__main__': main()
e24c2704d6ce4b73d521ab63cc3fff3fd9b04289
pista420/Pisteljic-vjezbe
/vjezbe/vjezba2.py
469
3.59375
4
def vjezba2(): from math import sin, cos, sqrt q = (3 + 4) * 5 print(q) n =eval(input("Unesite vrijednost: ")) m = n * (n-1)/2 print(m) r =eval(input("r ")) print(4 != r*r) a =eval(input("a")) p =eval(input("p")) t =sqrt(p*cos(a)*cos(a)+p*sin(a)*sin(a)) print(t) y1 =eval(input("y1")) y2 =eval(input("y2")) x1 =eval(input("x1")) x2 =eval(input("x2")) z = (y2 - y1) / (x2 - x1) print(z) vjezba2()
dc1b607b9028841fbbf9430ddccab50f54fe1cc0
shengzhc/sc-py
/src/gen_pipeline.py
481
3.90625
4
def find_prime(): num = 1 while num < 100: if num > 1: for x in range(2, num): if num % x == 0: break else: print("find_prime:", num) yield num num += 1 def find_odd_prime(seq): for num in seq: if (num % 2) != 0: print("find_odd_prime:", num) yield num a_pipeline = find_odd_prime(find_prime()) for _ in a_pipeline: pass
7003b1994fd3466de1524ce248f01caeed879eef
widderslainte/langmaker
/langmaker/morpheme.py
916
3.625
4
''' Generate linguistically consistent morphemes ''' from numpy.random import choice from langmaker.syllable import Syllable class Morpheme(object): ''' combine syllables into morphemes ''' # TODO: this may not be a necessary class affixes = {} def __init__(self, syllables=None): self.syllables = syllables or Syllable() def get_morpheme(self, length=None): ''' create a morpheme ''' # TODO: intelligently join syllables # TODO: consider free vs bound morphemes length = length or choice([1, 2, 3], 1, p=[0.5, 0.49, 0.01])[0] return ''.join([self.syllables.get_syllable() for _ in range(length)]) def get_affix(self, tag): if not tag in self.affixes: self.affixes[tag] = self.get_morpheme(length=1) return self.affixes[tag] if __name__ == '__main__': builder = Morpheme() print(builder.get_morpheme())
d9f8dfa0c8199ebc3d952a39ac99b2db18a075f9
ericzhai918/Python
/Python_Cookbook/Chapter02/0201.py
391
3.765625
4
#使用多个界定符分割字符串 import re line = 'asdf fjdk; afed, fjek,asdf, foo' a = re.split(r'[;,\s]\s*', line) print(a) #捕获分组 b = re.split(r'(;|,|\s)\s*',line) print(b) values = b[::2] print(values) delimiters = b[1::2]+[''] print(delimiters) c = ''.join(v+d for v,d in zip(values,delimiters)) print(c) #非捕获字符?: d = re.split(r'(?:;|,|\s)\s*',line) print(d)
bf470354b13e259fba8be7588cba03105664d09a
MrLVS/PyRep
/HW8.py
1,265
4.0625
4
import time """Функция для преобразования строки в число с помощью рекурсии. Проверяет возможность преобразования строки в число, если число четное, то делит его на 2, в противном случае на 3.""" def converting_str_to_int(): enter = input("""Введите текст.\n--> """) if enter.isdigit(): print("""Колдуем...\nОжидайте ответ.""") time.sleep(1.5) def str_to_int(text): if text: return (ord(text[-1]) - ord('0')) + 10 * str_to_int(text[:-1]) else: return 0 resNumber = str_to_int(enter) if resNumber % 2 == 0: print(resNumber / 2) else: print(resNumber * 3 + 1) converting_str_to_int() elif enter == "cancel": exit() elif not enter.isdigit(): print("Не удалось преобразовать текст в число, попробуйте еще раз.") print('Если хотите закрыть программу, введите "cancel"') converting_str_to_int() converting_str_to_int()
e5918102b325d4ebff4ba9e5ec1df70d73f94a23
Aasthaengg/IBMdataset
/Python_codes/p03555/s503295023.py
94
3.609375
4
s = list(input()) t = list(input()) t = t[::-1] ans = 'NO' if s == t: ans = 'YES' print(ans)
72cb8d54554b96e200d6c03972c8a7ddf4d2a6d9
ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck
/problems/AE114.py
439
3.890625
4
# Quickselect def quickselect(array, k): target = k-1 start = 0 pivotIndex = len(array)-1 while True: i = start for j in range(start, pivotIndex): if array[j] < array[pivotIndex]: swap(array, i, j) i += 1 swap(array, i, pivotIndex) if i == target: return array[target] if i > target: pivotIndex = i-1 if i < target: start = i+1 def swap(array, i, j): array[i], array[j] = array[j], array[i]
48e96f006e7f0e73f2c94ce490ad2d4f30bf3d0c
skylinelayla/PythonDemo
/Demo/HelloWorld.py
2,930
3.65625
4
print('Hello World') print(2**100) p=(4,5) x,y=p print(x) z=float(1+2.0+3) print(z) for x in [1,2,3]: print(x,end='') res=[c*4 for c in 'SPAM'] print(res) res=[] for C in 'SAPM': res.append(C*4) print(res) list(map(abs,[-1,-2,0,1,2])) L=['spam','Spam','SPAM!'] L[1]='eggs' print(L) if not 1: print('true') else: print('false') import threenames print(threenames.a,threenames.c) print(dir(threenames))#返回模块内部所有属性 S='SPAM' print(len(S)) print(S[0]) print(S[-1])#反向索引从有右边开始计算 print(S[-2]) print(S[1:3])#分片1到2 print(S[1:]) print(S[:]) #Python 不可以直接改变变量值,但可以重新创建一个相同名称的变量然后赋值 S='z'+S[1:] print(S) q=S.find('ps') print(q) S.replace('pa','XYZ')#但不会改变原来的变量 line='aaa,bbb,ccc,dd' print(line.split(',')) print(S.upper()) print('%s,eggs,and %s'%('spam','SPAM!')) print('{0},eggs,and {1}'.format('spam','SPAM!'))#高级格式化 L=[123,'spam',1.23] L.append('NI') L.pop(2) print(L)#大多数列表的方法可以直接改变列表的值 M=['bb','aa','cc'] M.sort() print(M) M.reverse()#翻转 print(M) M=[[1,2,3],[4,5,6],[1,8,9]] print(M) print(M[1]) #列表解析假设我们需要从矩阵中提取第二列 col2=[row[1] for row in M] print(col2) #print(row[1]+1 for row in M) diag=[M[i][i] for i in [0,1,2]] print(diag) douebles=[c*2 for c in 'spam'] print(douebles) G=(sum(row) for row in M) print(next(G)) #字典 D={'food':'spam','quantity':4,'color':'pink'} print(D['food']) print(D['quantity']+1) D['quantity']+=1 D['name']='Bob' D['job']='dev' print(D) res={'name':{'first':'Bob','last':'Smith'},'job':['dev','mgr'],'age':45.5} print(res) print(res['name']) print(res['name']['first']) print(res['name']['last']) print(res['job'][0]) print(res['job'].append('janitor')) print(res) D={'a':1,'b':2,'c':3} print(D) #字典的排序 Ks=list(D.keys()) print(Ks) Ks.sort() print(Ks) for key in Ks: print(key,'=>',D[key]) for key in sorted(D): print(key,'=>',D[key]) for c in 'spam': print(c.upper()) x=4 while x>0: print('spam!'*x) x-=1 #元组相当于一个不可以改变的列表 T=(1,2,34) print(len(T)) T+=(5,6) print(T) print(T.count(4))#元素4出现的次数 #文件操作--创建一个文件然后写入 f=open('data.txt','w') f.write('Hello\n') w=open('data.txt') text=w.readline() print(text)#读不出来??? #集合类型 X=set('spam') Y={'h','a','m'} print(X,Y) print(X&Y) print(X|Y) print(X-Y) print({k**2 for k in [1,2,3,4]}) #定义类 class Worker: def __init__(self,name,pay):#初始化了两个属性name和pay self.name=name self.pay=pay def lastName(self): return self.name.split()[-1] def giveRaise(self,percent): self.pay*=(1+percent) bob=Worker('Bob Smith',50000) sue=Worker('Sue Jones',60000) print(bob.lastName()) print(sue.lastName()) sue.giveRaise(.10) print(sue.pay)
8d464bc0655d1c2adfc1819d5760881768c00cf8
alvas-education-foundation/prasanna_p
/coding_solutions/12-07-2020_substring.py
185
4.34375
4
string=raw_input("Enter string:") sub_str=raw_input("Enter word:") if(string.find(sub_str)==-1): print("Substring not found in string!") else: print("Substring in string!")
3d22b02ac6b6566bb68a37dac0c9968d4066301d
wangweihao/Python
/11/11-15.py
233
3.6875
4
#!/usr/bin/env python #coding:UTF-8 def pri_str(s, n): if n == 0: return 0 print s[n-1] #反向 pri_str(s, n-1) #print s[n-1] 正向 if __name__ == '__main__': s = 'abcdef' pri_str(s, len(s))
fd6252305f50a1f577fdff8ed9b08207bc3c7917
Grulice/python-practice-book
/62.py
682
3.9375
4
"""Problem 62: Write a program wget.py to download a given URL. The program should accept a URL as argument, download it and save it with the basename of the URL. If the URL ends with a /, consider the basename as index.html.""" import urllib.request import os import sys # if no argument is provided - URL is set to bbc.com's home page try: URL = sys.argv[1] except IndexError: URL = 'http://www.bbc.com' urlPath = urllib.request.urlparse(URL)[2] # strip everything up to and incl. 1 lvl domain and params file = lambda: urlPath.split('/')[-1] if urlPath.split('/')[-1] != '' else 'index.html' # return basename urllib.request.urlretrieve(url=URL, filename=file())
564103dbf0bd2eb9bd5314be543ccf16f82d9567
SEVALOO/BOO
/HANGMAN.py
5,740
4.34375
4
# coding: utf-8 # In[ ]: import random # here it allows us to use the benefits of the functions random. #function 1 which is just a screen organized wordings def screen(): screeninstructions() name = input("Your Name : ") print('Welcome', name, 'This is a simple guessing game') print('____________________________________________________') print('Now', name, 'let the guessing begin with only 9 tries') print('make them count, lets goooo') #calling out the function hangman() print() #second functions that tells the person or the player a random fact as a treat of guessing correct def randomfact(animal): if animal == 'cheeta': print("did you know that cheetas reaches their max speed which is 65mph") elif animal == 'lion' : print("a lion's claws can reach lengths of up to 1.5 inches") elif animal == 'crocodile' : print("the smallest crocodile species is the dwarf crocodile which can be 5 feet in length and weigh up to 40-70lb") elif animal == 'giraff' : print("Giraffe's can eat 70-80 pounds of leaves a day and feed 16-20 hours") elif animal == 'monkey' : print("There are currently 264 known monkey species, but there are others to discover!") elif animal == 'zeebra' : print("Did you know that every zebra has a unique pattern of black and white stripes") elif animal == 'deer' : print("Each year, antlers fall off and regrow") elif animal == 'penguin' : print("The fastest species is the Gentoo Penguin, which can reach swimming speeds up to 22 mph") elif animal == 'Magpies' : print("Magpies Dont Like Shiny Things — They are Scared of Them because that is how their survival nature taught them") elif animal == 'parrot': print("Parrots are intelligent birds and like us humans they have feelings and can get sad and throw tantrums, fun right!") elif animal == 'camel' : print("Camels rarely sweat, even when ambient temperatures reach 49 °C and their title is The Ship Of The Desert") elif animal == 'leapord' : print("Sadly Leopards are predominantly solitary animals that have large territories and they fight to the death") elif animal == 'gazelle' : print("The tiny Thompsons gazelle's exhibit the very distinctive behavior of stotting which is jumping up to 10 feet") #a third function of the screeen before entering the game. explains the guesser what will happen. def screeninstructions(): print('instructions:') print('you will have 9 trials to guess what word has been picked') print('each mistak will cause you to lose a limb, be careful!') print('once the correct asnwer is found, you will learn a random fact about the animal') #main function which is all the actoin happens. def hangman(): #random picks one of these randomly word = random.choice(['crocodile','lion','cheeta', 'giraff', 'monkey','magpies', 'zeebra', 'deer', 'penguin','camel', 'leapord', 'gazelle','parrot']) #choosing randomly strictly only letters letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' #setting turns to 9 and slowly decreasing it to 0 turns = 9 guessed = '' #letters that are used by the player will be added here #conditional to keep going if input is still empty while len(word) > 0 : empty_string = '' #missed trials which are zero then increased by 1 each time the guess is wrong missed = 0 #conditional if word is one of the letters then add the letter to the empty string for letter in word: if letter in guessed: empty_string = empty_string + letter else: empty_string = empty_string + '_ ' + '' missed = missed + 1 #where the missed trials are increased after each attempt #if it is a word from the list then print the letter which is all the letters guessed if were correct if empty_string == word: print(empty_string) #funfact about the animal they guessed print("") print('Marvelous!you are correct! the word was', word) print("") print('fun fact about', word) print('') #calling the function randomfact onto word randomfact(word) break #stop the loop if his right print("Guessing Time! : ", empty_string) # other wise keep guessing guess = input().lower() #all ipnuts are lower cased even if user put upper case # if not a letter then will say invalid if guess in letters: guessed = guessed + guess else : print('Enter a valid letter! : ') guess = input().lower() # again lower case every letter or input #if guessed incorrect then decreas his turns by one if guess not in word: turns = turns - 1 if turns == 4: print("nice try but again") print(' o' ) if turns == 3: print("come on think about it a little bit") print(' o') print(' / \'') if turns == 2: print("Third time a charm ok what about a fourth from the north!") print(' o') print('/|\'') print('/ ') if turns == 1: print("OOOOOoooohhh so close dont lose hope") print(' o') print(' /|\ ') print(' / \ ') print('Your out of tries but good luck next time') break # In[1]: assert isinstance(random.choice, str)
c54b3fd733ad0c8adc617f08756a63d879c965ef
tryspidy/python-calculator-ESkGqo
/main.py
887
4.0625
4
print("Enter Your Choice 1(Add)/2(Sub)/3(Divide)/4(Multiply)") num = int(input()) if num == 1: print("Enter Number 1 : ") add1 = int(input()) print("Enter Number 2 : ") add2 = int(input()) sum = add1 + add2 print("The Sum Is ", sum) elif num == 2: print("Enter Number 1 : ") sub1 = int(input()) print("Enter Number 2 : ") sub2 = int(input()) difference = sub1 - sub2 print("The Difference Is ", difference) elif num == 3: print("Enter Number 1 : ") div1 = float(input()) print("Enter Number 2 : ") div2 = float(input()) division = div1 / div2 print("The Division Is ", division) elif num == 4: print("Enter Number 1 : ") mul1 = int(input()) print("Enter Number 2 : ") mul2 = int(input()) multiply = mul1 * mul2 print("The Difference Is ", multiply) else: print("enter a valid Number")
b7e91929d66ed1810650b45633e8cd3d13ab2974
plankobostjan/project-euler
/Problem10
768
3.953125
4
#!/usr/bin/python import math import time def isPrime(n): if n==1: return False elif n<4: # 2 and 3 are prime return True elif n%2==0: return False elif n<9: #4, 6 and 8 are already excluded return True elif n%3==0: return False else: r=int(math.sqrt(n)) f=5 while f<=r: if n%f==0: return False elif n%(f+2)==0: return False f+=6 return True def main(): suma = 0 for n in range(1,2000000): if isPrime(n): suma+=n print suma if __name__ == "__main__": start_time = time.time() main() print("--- %s seconds ---" % (time.time() - start_time))
658e8db3342847d7461a27192531d4c589f650d4
ferrerinicolas/python_samples
/5.3 Break And Continue/5.3.7 Higher Lower.py
259
4.125
4
magic_number = 3 #Your code here... while True: guess = int(input("Enter a guess: ")) if guess == magic_number: print("You got it!") break elif guess > magic_number: print("Too high!") else: print("Too low!")
6b988ea559b94dd89c2258ff83a6f0d31e71e908
SagittariuX/Interview_Ex
/DailyCode/Day80.py
776
3.8125
4
def deepest_node(node): return deepest_node_search(node, 1)[0] def deepest_node_search(node, depth): if(node == None): return ['' , depth] left = deepest_node_search(node.left, depth+1) right = deepest_node_search(node.right, depth+1) # if left is a null if not left[0]: left = [node, depth] # if right is a null if not right[0]: right = [node, depth] if left[1] >= right[1]: return left else: return right class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right tree = Node('a') tree.left = Node('b') tree.left.left = Node('d') tree.right = Node('c') print(deepest_node(tree).value)
1188496e017039e1f483d8246b936c3eb9a9698b
LostKe/python-study
/demo/Demo28.py
797
3.515625
4
# coding=utf-8 ''' 进程池 在Unix/Linux下,可以使用fork()调用实现多进程。 要实现跨平台的多进程,可以使用multiprocessing模块。 进程间通信是通过Queue、Pipes等实现的。 ''' from multiprocessing import Pool import os, time def run_process(name): print('run task [%s] ,pid=%s' % (name, os.getpid())) start = time.time(); time.sleep(.8) end = time.time(); print('task [%s] use %0.2f seconds ' % (name, (end - start))) if __name__ == '__main__': print('parent pid=%s' % os.getpid()) p = Pool(3) # 设置同时跑4个进程 for i in range(5): p.apply_async(run_process, args=(i,)) print('waiting for all process done....') p.close() p.join() print('all process has done')
b88c9db4184741625938ddaccdadb079f250b208
saipoojavr/saipoojacodekata
/binary.py
166
3.6875
4
num=str(input()) count=0 for i in range(0,len(num)): if (num[i]=='0' or num[i]=='1'): continue else: count=count+1 if(count>0): print("no") else: print("yes")
612af5d734eebe1c18f0b572119ef51735f9d5b3
Shinpei2/python_source
/sukkiri_python/chapter4/q4-6.py
522
3.734375
4
# (1) numbers = [1,1] pointer = 0 # 追加要素のうち、若い番号を指す変数pointer while True: add = numbers[pointer] + numbers[pointer +1] if add > 1000: break numbers.append(add) pointer += 1 print(numbers) # (2) ratios = [] for i in range(len(numbers) -1): add = numbers[i+1] / numbers[i] ratios.append(add) print(ratios) # (3) 1000倍して、int型に変換後、1000で割る for i in range(len(ratios)): ratios[i] = int(ratios[i] * 1000) / 1000 print(ratios)
8b3f9377370204de4c74ca442619b14ab38642f0
suziesu/Python-Coursera
/Rock-paper-scissors-lizard-Spock.py
1,560
4.125
4
import math import random # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors def name_to_number(name): if name == "rock": number = 0 elif name == "Spock": number = 1 elif name == "paper": number = 2 elif name == "lizard": number = 3 elif name == "scissors": number = 4 else: print "Not A Valid item!" number = -1 return number def number_to_name(number): if number == 0: name = "rock" elif number == 1: name = "Spock" elif number == 2: name = "paper" elif number == 3: name = "lizard" elif number == 4: name = "scissors" else: print "Number is not Valid" name = False return name def rpsls(player1, player2): result = (player1-player2) % 5 if result == 0 : return 0 elif result >= 3: return -1 # player 2 win elif result <3 and result >0: return 1 #player 1 win if __name__ == "__main__": while True: print "\n" player_choose = raw_input("Player choose :") player_number = name_to_number(player_choose) computer_number = random.randrange(0,5) computer_choose = number_to_name(computer_number) print "Computer Choose: %s" %(computer_choose) if player_number >= 0 and computer_choose: out = rpsls(player_number, computer_number) if out == 0: print "it is a tie" elif out == 1: print "Player Win" elif out == -1: print "Computer Win" else: print "Wrong output" else: print "Input is Wrong or Computer is Wrong!"
31a079b295955e1741554cec661aec9b1d610203
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_3_neat/16_0_3_snandi_gcjC.py
1,885
3.53125
4
import string import math import itertools def fermat(n): if n == 2: return True if not n & 1: return False return pow(2, n-1, n) == 1 def int2base(x, base): digs = string.digits if x < 0: sign = -1 elif x == 0: return digs[0] else: sign = 1 x *= sign digits = [] while x: digits.append(digs[x % base]) x /= base if sign < 0: digits.append('-') digits.reverse() return ''.join(digits) def findFactor(x): if fermat(x): return -1 else: p = int(math.sqrt(x) + .5) + 1 for i in itertools.count(2): if x%i == 0: return i if i > math.sqrt(x) + 1: break return -1 def main(): N = 16 J = 50 num = ["1" for x in range(N)] printLines = [] for attempt in xrange(2**(N-2)): #print attempt outputLine = "" prime = False s = bin(attempt)[2:].zfill(N-2) num[1:-1] = s currentnum = "".join(num) for b in range(2, 11): #print b converted = int(currentnum, b) #print "converted", converted factor = findFactor(converted) if factor != -1: outputLine += " " + str(factor) else: prime = True break if not prime: print currentnum outputLine = str(currentnum) + outputLine + "\n" printLines.append(outputLine) if len(printLines) == J: return printLines fout = open("c.out", "w") fout.write("Case #1:" + "\n") output = main() for l in output: fout.write(l) fout.close()
0ef35f5a3d4e6e1247d0541382cb6be1b1065871
ihongChen/Effective-python-ex
/28_collection_abc.py
530
3.609375
4
class FrequencyList(list): def __init__(self,members): super(FrequencyList,self).__init__(members) def frequency(self): counts = {} for item in self: counts.setdefault(item,0) counts[item] += 1 return counts foo = FrequencyList(['a','b','a','c','b','a','d']) print 'length is {}'.format(len(foo)) # length is 7 print 'frequency:',foo.frequency() # frequency: {a:3,b:2,c:1,'d':1} foo.pop() print 'After pop:',repr(foo) ## bar = [1,2,3] bar[0] bar.__getitem__(0)
03374b36abb34fec4a3d52745f23062fd5706d98
stepahn/slf
/tests/test_more_builtins.py
3,298
3.5625
4
import py from interpreter import Interpreter def test_int_add(): w_module = do_the_twist(""" x = 0 x = x add(4) x = x add(8) x = x add(15) x = x add(16) x = x add(23) x = x add(42) """) assert w_module.getvalue("x").value == 108 def test_int_sub(): w_module = do_the_twist(""" x = 0 x = x sub(4) x = x sub(8) x = x sub(15) x = x sub(16) x = x sub(23) x = x sub(42) """) assert w_module.getvalue("x").value == -108 def test_int_mult(): w_module = do_the_twist(""" x = 1 x = x mul(4) x = x mul(8) x = x mul(15) x = x mul(16) x = x mul(23) x = x mul(42) """) assert w_module.getvalue("x").value == 7418880 def test_int_div(): w_module = do_the_twist(""" x = 108 div(6) y = 42 div(5) z = 42 div(11) """) assert w_module.getvalue("x").value == 18 assert w_module.getvalue("y").value == 8 assert w_module.getvalue("z").value == 3 def test_int_div(): w_module = do_the_twist(""" x = 108 mod(6) y = 42 mod(5) z = 42 mod(11) """) assert w_module.getvalue("x").value == 0 assert w_module.getvalue("y").value == 2 assert w_module.getvalue("z").value == 9 assert w_module.getvalue("x").istrue() == False assert w_module.getvalue("y").istrue() == True def test_bool_and(): w_module = do_the_twist(""" a = bool and(1,1) b = bool and(1,0) c = bool and(0,1) d = bool and(0,0) """) assert w_module.getvalue("a").istrue() == True assert w_module.getvalue("b").istrue() == False assert w_module.getvalue("c").istrue() == False assert w_module.getvalue("d").istrue() == False def test_bool_eq(): w_module = do_the_twist(""" x = bool eq(1,2) y = bool eq(1,1) """) assert w_module.getvalue("x").istrue() == False assert w_module.getvalue("y").istrue() == True def test_compare_int(): w_module = do_the_twist(""" a = 1 eq(0) b = 1 neq(0) c = 1 eq(1) d = 1 neq(1) """) assert w_module.getvalue("a").istrue() == False assert w_module.getvalue("b").istrue() == True assert w_module.getvalue("c").istrue() == True assert w_module.getvalue("d").istrue() == False def test_bool_nor(): w_module = do_the_twist(""" a = bool nor(1,1) b = bool nor(1,0) c = bool nor(0,1) d = bool nor(0,0) """) assert w_module.getvalue("a").istrue() == False assert w_module.getvalue("b").istrue() == False assert w_module.getvalue("c").istrue() == False assert w_module.getvalue("d").istrue() == True def test_bool_not(): w_module = do_the_twist(""" x = bool not(0) y = bool not(1) """) assert w_module.getvalue("x").istrue() == True assert w_module.getvalue("y").istrue() == False def test_bool_gz(): w_module = do_the_twist(""" x = bool gz(-1) y = bool gz(0) z = bool gz(1) """) assert w_module.getvalue("x").istrue() == False assert w_module.getvalue("y").istrue() == False assert w_module.getvalue("z").istrue() == True def test_math_pow(): w_module = do_the_twist(""" x = 2 pow(1) y = 2 pow(2) z = 2 pow(3) """) assert w_module.getvalue("x").value == 2 assert w_module.getvalue("y").value == 4 assert w_module.getvalue("z").value == 8 def do_the_twist(code): from simpleparser import parse ast = parse(code) interpreter = Interpreter() w_module = interpreter.make_module() interpreter.eval(ast, w_module) return w_module
eae0d5943a42e9dad6bdc46295283c69cf30f1ff
ayanez16/Tarea-1-Estructura
/Ejercicio11.py
367
3.734375
4
#Calcular la suma de los cuadrados de los primeros 100 enteros y escribir el resultado. class Ejercicio11: def __init__(self): pass def cicloFor(self): i = 1 suma = 0 for i in range(100): suma=suma+i*1 print("La suma de los cuadrados es: ",suma) resultado=Ejercicio11() resultado.cicloFor()
0b3b77ad5913c0dc332b0981b5eb5a075225b801
kkaixiao/pythonalgo2
/beat_codility_034_maximum_slice.py
1,071
3.921875
4
''' A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + … + A[Q]. Write a function: def solution(A) that, given an array A consisting of N integers, returns the maximum sum of any slice of A. For example, given array A such that: A[0] = 3 A[1] = 2 A[2] = -6 A[3] = 4 A[4] = 0 the function should return 5 because: (3, 4) is a slice of A that has sum 4, (2, 2) is a slice of A that has sum −6, (0, 1) is a slice of A that has sum 5, no other slice of A has sum greater than (0, 1). ''' def max_slice(arr): global_max = arr[0] local_max = arr[0] for i in range(1, len(arr)): temp_sum = local_max + arr[i] if temp_sum > arr[i]: local_max = temp_sum if local_max > global_max: global_max = local_max else: local_max = arr[i] return global_max arr1 = [5, -4, 8, -10, -2, 4, -3, 2, 7, -8, 3, -5, 3] print(max_slice(arr1))
074a327a6bacfd4aeb8ee47f1aa6c8f1f274428c
Sajid305/Python-practice
/Source code/Lambda Expression/Lambda Expression.py
289
4.0625
4
# Lambda Expression # def add(a,b): # return a+b # print(add(3,4)) # ab = lambda a,b : a+b # print(ab(1,2)) # we use lambda with some built in function like map,filter etc; # multiply = lambda a,b : a*b # print(multiply(2,3))
17f47f942acdd93b5c1b86366e661d3ec5098056
albertojr/estudospython
/ex025.py
103
3.9375
4
nome = input('Digite um nome:').strip().upper() print('tem SILVA no nome?\n{}'.format('SILVA' in nome))
5085edea06c53a107891df1947d5a850a96af6ba
qwopper/py-timechamber
/First_Project01/Python Crash Course/Lists/Editing Lists.py
1,027
4.46875
4
mari_favorite_food = [] mari_favorite_food.append("MackyCheese") mari_favorite_food.insert(0,"Pizza") mari_favorite_food.append("Chocolate") mari_favorite_food.insert(4, "Poms") print(mari_favorite_food) # Regular List mari_favorite_food.reverse() # Reversed list: .reverse() print(mari_favorite_food) mari_favorite_food.sort() # Sorted list in alphabetical order: .sort() print(mari_favorite_food) mari_favorite_food.sort(reverse=True) # Reverses list in sort: .sort(reverse=True) print(mari_favorite_food) print(sorted(mari_favorite_food)) # Sorts list only in the print function temporarily: print(sorted(list name here)) print(mari_favorite_food) # List comes back to normal after sorted print function popped_mari_fav_food = mari_favorite_food.pop() # Takes element from from list temporarily: .pop() print(mari_favorite_food) print(f'The last thing Mari ate is {popped_mari_fav_food}!') nums = [] # Shaun's example of a squared list from 0-12 i = 0 while i < 12: nums.append(i*i) i += 1 print(nums)
6176a9e1fd147ffbb3fd26008b4b59b3ae1b5b0b
jimmyhmiller/project-euler
/solutions/euler23.py
407
3.6875
4
#!/usr/bin/env python from util import proper_divisors def abundant(n): return sum(proper_divisors(n)) > n def abundantsum(i, all_abundants): return any(i-a in all_abundants for a in all_abundants) def main(): all_abundants = set(i for i in range(1,28123) if abundant(i)) print sum(i for i in range(1,28123) if not abundantsum(i, all_abundants)) if __name__ == '__main__': main()
6479c1a6f3742ed734fec0d42a82a95223fbbdec
nbro/ands
/ands/algorithms/matching/gale_shapley.py
10,783
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 19/09/2017 Updated: 29/09/2017 # Description The Gale-Shapley algorithm for the stable matching problem, which is a discrete problem. Given n men and n women and a list of preferences for each man and woman, regarding who they want to stay with. A "perfect matching" is an one-to-one assignment of each man to exactly one woman, so that no man or woman remains unmatched (or "alone"). An unstable match occurs when man M prefers woman W and woman W prefers man M, but man M is matched with another woman W' and woman W is with another man M'. A "stable matching" is a perfect matching with no unstable pairs. Stable matching problem: find a stable matching (if one exists). Clearly, domains could be different. Instead of women and men we could have for example people and servers, medical school graduates and hospitals, intern to companies, etc. How do find matches so that no men or women remain alone and no unstable match exists? We can use the Gale-Shapley algorithm (proposed 1962) to solve this problem, whose pseudo-code is as follows: function GALE_SHAPLEY: Initialize all m ∈ M and w ∈ W to free while ∃ free man m who still has a woman w to propose to: w = first woman on m’s list to whom m has not yet proposed if w is free: (m, w) become engaged else some pair (m', w) already exists: if w prefers m to m': m' becomes free (m, w) become engaged else: (m', w) remain engaged ## Examples Suppose we have the following preferences lists for men. | | 1st | 2nd | 3rd | |--------|--------|--------|-------| | Xavier | Amy | Bertha | Clare | | Yancey | Bertha | Amy | Clare | | Zeus | Amy | Bertha | Clare | And the following one for women. | | 1st | 2nd | 3rd | |--------|--------|--------|------| | Amy | Yancey | Xavier | Zeus | | Bertha | Xavier | Yancey | Zeus | | Clare | Xavier | Yancey | Zeus | Then assignments Xavier to Clare, Yancey to Bertha and Zeus to Amy are unstable, because Bertha prefers Xavier to Yancey and Xavier prefers Bertha to Clare. The assignments Xavier to Amy, Yancey to Bertha and Zeus to Clare are stable. ## Notes 1. Men propose to women in decreasing order of preference. 2. Once a woman is matched, she never becomes unmatched: she only "trades up." ## Complexity analysis of the Gale-Shapley algorithm Gale-Shapley terminates with a stable matching after at most n² iterations of the while loop. In particular, n * (n - 1) + 1 proposals may be required. ### Algorithm terminates after at most n² iterations of while loop. #### Proof - There are n² pairs (m, w). - At each iteration of the while loop, one man proposes to one woman. - Once a man proposes to a woman, he will never propose to her again (note 1). Thus, a man does at most n proposals. - Thus, after at most n² iterations, no one is left to propose to (algorithm must terminate). ### All men and women get matched (we have a perfect matching) - Suppose (by contradiction) that there is a man, Z, who is not matched upon termination of algorithm. - Then there must be a woman, say A, who is not matched upon termination. Remember there are n men and n women! - Then, by note 2, A was never proposed to. - But, Z proposes to everyone, since he ends up unmatched. Thus, he must have proposed to A, a contradiction. ### No unstable pairs (stable matching) Suppose we have the following pairs (Xavier-Clare), (Yancey-Bertha) and (Zeus-Amy). And suppose Xavier prefers Bertha to Clare and Bertha prefers Xavier to Yancey, i.e. Xavier and Bertha would hook up with each other after the given assignments. So we have an unstable pair in a Gale-Shapley matching S. Then there are two possible cases: 1. Xavier never proposed to Bertha. => Xavier prefers his partner to Bertha in S. => S is stable. 2. Xavier proposed to Bertha. => Bertha rejected Xavier (right away or later). Remember: women only trade up. => Bertha prefers her current partner to Xavier. => S is stable. In both cases 1 and 2, we reach a contradiction. ▪ ## How to implement the Gale-Shapley algorithm so that its complexity is O(n²)? Since there are at most n² iterations, each iteration should take constant time. We denote men and women from 0 to n - 1. We maintain two lists wife[m] and husband[w]. wife[m] or husband[w] is None if m does still not have a woman and w does still not have a husband, respectively. Initially, all wife[i] and husband[i], for i = 0, ..., n - 1, is None. For each man, maintain a list of women, ordered by preference. Maintain a list count[m] that counts the number of proposals made by man m. Idea: for each woman, create the inverse of her preference list. For example, if the preference list of woman w is: 0 1 2 <- preferences [2, 0, 1] <- men where 2 is w's most preferred man and 1 the least preferred. Then we build the following inverse list 0 1 2 <- men [2, 1, 0] <- preferences where the number 0 represents the highest preference and the number 2 the smallest one. To build the inverse preference list, it takes n time. Suppose we have an n x n matrix, where each row i represents the preferences list of man (or woman) i. Then, we can invert those preferences lists as follows: inverses := empty n x n matrix for i = 0 to n - 1: for p = 0 to n - 1: inverses[preferences[i][p]] = p ### Conclusions We have n men + n women = 2 * n. But we also have as input the preferences lists of men and women. Each of them occupies n² space. So, the input is N = 2 * n². It actually follows that the Gale-Shapley algorithm is a O(N) algorithm, i.e. a linear-time algorithm, where N is the size of the input. ## Further Notes - In practical applications, the input size may be linear as the preference list may be limited to a constant (say 5 < n), where n is the number of men (or women). - With the previous restriction, the algorithm may fail to find a stable matching. - In practice, a "reasonably" stable matching is sufficient. - The previous algorithm assumed we have the same number of men as women. ## Understanding the Solution produced by Gale-Shapley algorithm. TODO # TODO - is_stable function - Implement the GaleShapley algorithm for the Hospitals-Students matching problem. # References - Slides of prof. E. Papadopoulou for her course "Algorithms & Complexity" at USI, fall 2017, master in AI. - https://en.wikipedia.org/wiki/Stable_marriage_problem """ __all__ = ["gale_shapley"] def _validate_inputs(men_preferences: list, women_preferences: list, n: int): if len(men_preferences) != len(women_preferences): raise ValueError("Preferences lists should be of the same size.") for m, w in zip(men_preferences, women_preferences): if len(m) != len(set(m)) or len(w) != len(set(w)): raise ValueError("A preference list has duplicate entries.") if len(m) != n or len(w) != n: raise ValueError("Preferences matrix should be n x n.") possible_values = set(range(n)) for p1, p2 in zip(m, w): if p1 not in possible_values or p2 not in possible_values: raise ValueError("Preferences must be in range [0, n - 1].") def _build_inverses(women_preferences: list) -> list: """Builds the inverse matrix of the preferences matrix for women, according to the algorithm described in the doc-strings above of this module. Time complexity: Θ(n²).""" n = len(women_preferences) inverses = [[None for _ in range(n)] for _ in range(n)] for w in range(n): for p in range(n): # p for preference. inverses[w][women_preferences[w][p]] = p return inverses def gale_shapley(men_preferences: list, women_preferences: list) -> list: """Suppose we have n = len(men_preferences) = len(women_preferences) men and women. We number men and women from 0 to n - 1. Time complexity: O(n²), where n = # of men = # of women, or O(N), where N is the number of preference lists, i.e. N = n². In other words, this is a linear-time algorithm in terms of the size of the input.""" n = len(men_preferences) _validate_inputs(men_preferences, women_preferences, n) # To keep track of wives of men. So, wife[m] is the wife of m. wife = [None] * n # To keep track of husbands of women. So, husband[w] is the husband of w. husband = [None] * n inverses = _build_inverses(women_preferences) # To keep track of the number of proposals made by men. So, count[m] is the # number of proposals of man m. count = [0] * n def next_man() -> int: """Returns the index or number of the next man without a woman, or None if there is not such man.""" for i, w in enumerate(wife): if w is None: return i def hook_up_with(m: int, w: int) -> None: # Assign m to be the current partner of w. husband[w] = m # Assign w to be the current partner of m. wife[m] = w def go_forward(m: int) -> None: """Makes m man go forward and forget about its current preference, i.e. m now goes forward to his next preference.""" count[m] += 1 assert 0 < count[m] < n def make_alone(o: int) -> None: wife[o] = None go_forward(o) def prefers(w: int, m: int, o: int) -> bool: """Returns true if w prefers m over o.""" assert m != o return inverses[w][m] < inverses[w][o] m = next_man() while m is not None: # If there's still a man m without a woman. # This while loop takes at most n² iterations. # All of the following operations take O(1) time. # Look up the next preferred woman for m. w = men_preferences[m][count[m]] # If w does not have a partner. if husband[w] is None: hook_up_with(m, w) else: # w is already matched with some man. # Get the current partner of w. o = husband[w] assert wife[o] == w # If w prefers m over o, then make m the new partner of w and make # o alone. if prefers(w, m, o): hook_up_with(m, w) make_alone(o) else: go_forward(m) m = next_man() # Assert that at the end of the while loop all men and women have a partner. assert all(x is not None for x in wife) assert all(x is not None for x in husband) return wife, husband
553a424c0d0584a8a466a382621440ea3de55ef2
PhillipRamdas/stock-broker-selector
/stockCalculator.py
2,489
3.8125
4
#Tejpal Ramdas and Richard Wong; 7/18/19; FinTechFocus Wells Fargo #Displays online stock broker with lowest cost depending on intial expected trade. # csv file for data, parse for dictionaries stockBrokers = { "TD": {"minDeposit":0,"FeePerTrade" : 6.95, "FeePerShare" : 0}, "Cobra Trading" : {"minDeposit": 30000 ,"FeePerTrade" : 0, "FeePerShare" : 0.004} } stocks= { "AMD": {"currPrice": 33.06, "yearChange": 16.21}, "GOOGL": {"currPrice": 1143.61, "yearChange": 1212.91} } choices = {} def strStocks(): s = "Stock choices: " for i in stocks: s += i + ", " return s def countShares(): count = 0 for stock in choices: count += choices[stock] return count def promptStockInput(): stock = input("Which stock would you like to invest in? ") print(stock + " is $" + str(stocks[stock]["currPrice"]) + " per share") shares = input("How many shares would you like? ") return stock, shares def overMin(): total = 0 brokers=[] for stock in choices: total += stocks[stock]["currPrice"]* choices[stock] for broker in stockBrokers: if stockBrokers[broker]["minDeposit"] <= total: brokers.append(broker) return brokers def bestPossibleStockBroker(brokers): for broker in brokers: #Initializes lowestCost to number of trades times fee per trade + number of stocks traded times fee per stock traded lowestCost = len(choices)*stockBrokers[brokers[0]]["FeePerTrade"] + countShares()*stockBrokers[brokers[0]]["FeePerShare"] for broker in brokers: if (lowestCost > len(choices)*stockBrokers[broker]["FeePerTrade"] + countShares()*stockBrokers[broker]["FeePerShare"]): lowestCost = len(choices)*stockBrokers[broker]["FeePerTrade"] + countShares()*stockBrokers[broker]["FeePerShare"] lowestCostBroker = broker return broker , lowestCost def main(): moreStocks = True while (moreStocks): stock, shares = promptStockInput() choices[stock] = int(shares) moreStocks = input("Would you like add more stocks? (yes/no) ") if moreStocks.lower() == "yes": moreStocks = True else: moreStocks = False lowestbroker = bestPossibleStockBroker(overMin()) print("You should choose " + lowestbroker[0] + "as your stock broker because it only costs you $" + str(lowestbroker[1]) + " for your initial trade.") if(__name__=="__main__"): main()
feb89ecb0eff3e55372d145f68618c966380e461
arshdeepsinghsandhu/lab6
/task1.py
305
4.15625
4
import math class Point(): """represents the point in 2-D space""" x=0 y=0 p1 = Point() p1.x = 3 p1.y = 3 p2 = Point() p2.x = 5 p2.y = 5 def distance_between_points(p1,p2): distance = math.sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2) return (distance) print(distance_between_points(p1,p2))
f70fd19e1bb4c6e5a7cc35cd88f2f447782d462b
dawbit/-SEM3-JS
/kolokwium-python/zad3/zad3.py
419
3.5
4
def Transpose(matrix): transposed = [] for i in range(len(matrix[0])): transposed.append([row[i] for row in matrix]) f = open("macierzwynikowa.txt","w") for r in transposed: f.write(str(r)+'\n') matrix = [] with open("macierzwejsciowa.txt", "r") as f: contents = f.read().split('\n') for element in contents: matrix.append(element.split()) Transpose(matrix)
969fe41607248b9975a9ac7fe26d2eb3213f77a0
FredC94/MOOC-Python3
/UpyLab/UpyLaB 3.12 - Boucle While.py
1,069
3.9375
4
""" Auteur: Frédéric Castel Date : Avril 2020 Projet : MOOC Python 3 - France Université Numérique Objectif: Écrire un programme qui lit en entrée une valeur naturelle n et qui affiche à l’écran un triangle supérieur droit formé de X (voir exemples plus bas). Consignes: Attention, nous rappelons que votre code sera évalué en fonction de ce qu’il affiche, donc veillez à n’imprimer que le résultat attendu. En particulier, il ne faut rien écrire à l’intérieur des appels à input (int(input())et non int(input("Entrer un nombre : ")) par exemple). Il n’est pas demandé de tester si la valeur n est bien positive ou nulle, vous pouvez supposer que ce sera toujours le cas pour les valeurs transmises par UpyLaB. """ nbr = int(input()) lettre = "X" y = 0 z = 0 nbr2 = nbr print (nbr2 * lettre) espace = " " while y != nbr: # print ((z * (" ")), nbr2 * lettre) print("", nbr2 * lettre, sep=z * espace, end='\n') y = y + 1 z = z + 1 nbr2 = nbr2 -1 espace = " " print("", nbr2 * lettre, sep=espace, end='\n')
fce409e91f07838ec8596c2ffee63c9502618a90
1ekrem/python
/CrashCourse/chapter9/electric_car.py
814
4.03125
4
from car2 import Car class ElectricCar(Car): """Represent aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year, battery_size): """Initialize attributes of the parent class.""" super().__init__(make,model,year) self.battery_size = battery_size # Define a new method for the child class def describe_battery(self): """Print a statement describing the battery size.""" print("This car has a " + str(self.battery_size) + "-kWh battery.") def fill_gas_tank(self): """Electric cars do not have gas tank""" print("This car does not require a gas tank!") my_tesla = ElectricCar('Tesla', 'Model S', '2020',80) print(my_tesla.get_descriptive()) my_tesla.describe_battery() my_tesla.fill_gas_tank()
0ebad1a17cae9b71da3e0f140b1195d0d2367f19
SatyaSaiKrishnaAdabala/Python
/Magical Adder.py
341
3.703125
4
# Prompt to Enter 3 numbers print('Please enter 3 values separated by ,') adder = str(input()) new_adder = adder.split(",") #print(new_adder) a =0 b =0 for i in range(len(new_adder)): if i != len(new_adder) -1: a = a + int(new_adder[i]) else: b = int(new_adder[i]) print(a - b)
62d34f53a47d2e6eebf2207456076b5a825f6522
onkcharkupalli1051/pyprograms
/ds_nptel/test 2/8.py
1,212
4
4
""" Question 8 Write a Python function maxaggregate(l) that takes a list of pairs of the form (name,score) as argument, where name is a string and score is an integer. Each pair is to be interpreted as the score of the named player. For instance, an input of the form [('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)] represents two scores of 73 and 7 for Kohli, two scores of 33 and 90 for Ashwin and one score of 122 for Pujara. Your function should compute the players who have the highest aggregate score (aggegrate = total, so add up all scores for that name) and return the list of names of these players as a list, sorted in alphabetical order. If there is a single player, the list will contain a single name. For instance, maxaggregate([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)]) should return ['Ashwin'] because the aggregate score of Kolhi is 80, of Ashwin is 123 and of Pujara is 122, of which 123 is the highest. """ def maxaggregate(l): dic = {} for i in l: if i[0] in dic: dic[i[0]] += i[1] else: dic[i[0]] = i[1] m = max(list(dic.values())) x = [] for i in dic: if dic[i] == m: x.append(i) return sorted(x)
edba17f8a32e9cc6ec25088102d37096507cd2f3
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/crswad001/question2.py
792
4.09375
4
'''Wade Cresswell Question 2''' string = input("Enter a message:\n") def numpair(stringused): z = len(stringused) if z == 1: return 0 #if string gets to the point where the length is 1, dont add anything to the pair counter if z!=1 and z!=2: #if the string is currently not 1 or 2 letters long if stringused[0]==stringused[1]: stringused=stringused[2:] return 1 + numpair(stringused) #if the two alternate characters are equal, return the rest of the string else: return numpair(stringused[1:]) #otherwise return the rest of the string else: if stringused[0]==stringused[1]: return 1 else: return 0 print('Number of pairs:',numpair(string)) #prints the number of pairs in the string
6fd85ecfe26a2bb9cc8345727b0def001fb0fd27
EsaikaniL/python-2
/B104.py
60
3.546875
4
n=int(input("enter N")) k=int(input("enter K")) print(n**k)
1b0096acf4595fb93cd32ae262d82140349d764d
shengu4098/C109156121
/11.py
206
3.546875
4
def breakdown(a): c=0 for i in range(1,a): if a%i==0: c+=i return c n=int(input("請輸入正整數n:")) if n==breakdown(n): print("perfect") else: print("deficient")
5e1b007ef9ef0c1435903c379eea78d860decc21
vigneshdemitro/Guvi
/Python/loop/odd_100.py
381
4.34375
4
# Write a program to print all even numbers between 1 to 100. - using while loop """ Positive test case: Output : 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 """ i = 1 while i < 100: if i % 2 == 0: i += 1 elif i % 2 != 0: print(i, end=' ') i += 1
66e04036d0fb850aefd1c8743cecd84f142bde8c
rozenborg/checkpoint-1
/test/import unittest.py
471
3.515625
4
import unittest from app import office.Office class RoomTest(unittest.TestCase): def test_add_occupant(self): room = Office("Moon", 6) person = Fellow("Jerk", 100, "Male", "Y", "D1") room.add_occupant(person) self.assertEqual(1, room.get_occupant_count()) person = Staff("Hero", 12, "Female", "Training Warrior", "Training Department") room.add_occupant(person) self.assertEqual(2, room.get_occupant_count()) if __name__ == '__main__': unittest.main()
aae1a6876bddb9c69ef38a4cbd3f7288d6939293
mariomaldonado007/Python
/variables.py
803
4.09375
4
# Mis variables son las siguinetes mensaje = "Hola Mundo" # variables string van siempre entre comillas mi_entero = -10 mi_flotante = 3.1416 mi_complejo = 5+3j #para imprimir los valores de las variables e imprimimos print (mensaje) print ("el valor de mi entero", mi_flotante) print ("el valor de mi complejo", mi_complejo) print() print ("el valor de mi entero", mi_entero) # Imprimir tipos var = 2.0 tipo=type(var) print(tipo) # Aqui estoy imprimiendo el tipo de varible que estoy metiendo dummy = "23" print (type (dummy)) print (dummy) dummy = "56" print (dummy) print (type (dummy)) print() print() dummy = ("56") #actualizamos la variable dummy a 56 en forma string valor = int (dummy) # estamos asignando una nueva variable y convirtiendola de int print ( valor, type (valor))
8a6bc6aabb79db52dd0ab8b096cbe7471613b6ad
jdnorton22/LAPython
/lab5.py
272
4.34375
4
# take a single number in fizzbuzz # divisible by 5 or 3, or both value = int(input("Enter an integer value: ")) if value % 5 ==0 and value % 3 ==0: print("Fizz buzz") elif value % 5 ==0: print("Buzz") elif value % 3 ==0: print("Fizz") else: print(value)
33f00468558d1ad44380d7a50929be6bc28381c0
westondlugos/Dlugos_Weston
/ProgrammingLesson_06/graph.py
207
3.921875
4
size = int(input("What is the size of the table?")) slope = int(input("What is the slope?")) intercept = int(input("What is the y intercept?")) for i in range(0,size+1): print(i,(i * slope)+ intercept)
accef1a7c6e980ed7154fea0e026586db804af62
March13th/March13th
/Python/Mind map/python编程快速上手/第六章/project6_7.py
359
3.65625
4
tableData = [['apples','oranges','cherries','banana'], ['Alice','Bob','Carol','David'], ['dogs','cats','moose','goose']] def printTable(alist): for i in range(len(alist[0])): for j in alist: width=max([len(k) for k in j]) print(j[i].rjust(width),end=" ") print('\n') printTable(tableData)
a7ccdababd732a41f77501f79ec6ff8014ff0e56
ayoubabounakif/edX-Python
/strings_n_letter_words.py
853
4.21875
4
def find_n_letter_words(string, n): words = string.split() #print (words) iteration = 0 for x in words: if len(x) == n: #print (x) iteration = iteration + 1 return iteration test_string = "Python is an interpreted high-level programming language \ for general-purpose programming. Created by Guido van Rossum \ and first released in 1991, \ Python has a design philosophy that emphasizes code readability\ notably using significant whitespace. \ It provides constructs that enable clear programming on both small and large scales." total_words = 0 for k in range(1, 11): output = find_n_letter_words(test_string, k) total_words = total_words + output print ("There are", output,"words with", k,"characters.") print ("****\nThere are", total_words, "words in this string")
236b031236de55edec1f44f96fd6a8618a45e9fe
pchaow/SETask
/input_basic/student/answer1.py
176
4.03125
4
def answer1() : name = input("Enter Your name : ") country = input("Enter Your Country : ") print(f"My name is {name}. I came from {country}") answer1()
2e7bf5a9ec39c66171fa32726331adde66447600
ascentai/flatlands-gym
/flatlands/envs/flatlands_sim/vehicle_model.py
19,282
3.53125
4
# -*- coding: utf-8 -*- """ Bicycle vehicle model module. Also known as single-track model. Inherits basic functionalities from the PointModel This model overwrites the single point model with some extensions. Instead of just going towards a direction, it has a front and back wheel (separated by 'wheelbase') and turns along an arc. Its pose ([x, y, theta]) represents its rear axle, Mass, friction, etc. are not included in this model. Mostly based on this: https://nabinsharma.wordpress.com/2014/01/02/kinematics-of-a-robot-bicycle-model/ """ from abc import ABCMeta, abstractmethod import random import logging from math import pi, sin, cos, tan import numpy as np import pygame from .geoutils import offset LOGGER = logging.getLogger("vehicle") class IVehicleModel: __metaclass__ = ABCMeta def __init__(self, x, y, theta=0.0, vehicle_id="Base model", debug=False): """ Interface for vehicle models. All models should implement a reference point which corresponds to its pose, velocity, and acceleration. This can be the center of mass or anything else but it should be the egocentric reference point of the vehicle. :param x: starting coord in meters :param y: starting coord in meters :param theta: starting heading angle [optional] :param vehicle_id: string identifier of this object [optional] :param debug: turns on or off debug messages (verbose mode) [optional] """ self._id = vehicle_id self._debug = debug # save initial pose so that we can reset later self._initial_pose = np.array([x, y, theta % (2 * pi)]) self._pose = self._initial_pose self._velocity = 0.0 self._acceleration = 0.0 def __str__(self): return 'Agent ID: {0} - pose: {1} - velocity: {2} - acceleration {3}'.format( self._id, self.pose, self.velocity, self.acceleration) #region Properties @property def sprite(self): raise NotImplementedError("Unimplemented abstract base method") @property def pose(self): raise NotImplementedError("Unimplemented abstract base method") @property def position(self): raise NotImplementedError("Unimplemented abstract base method") @property def orientation(self): raise NotImplementedError("Unimplemented abstract base method") @property def velocity(self): raise NotImplementedError("Unimplemented abstract base method") @property def acceleration(self): raise NotImplementedError("Unimplemented abstract base method") #endregion #region Public methods @abstractmethod def move_accel(self, a=None, alpha=None): raise NotImplementedError("Unimplemented abstract base method") @abstractmethod def move_velocity(self, v=None, alpha=None): raise NotImplementedError("Unimplemented abstract base method") #@abstractmethod # TODO we used this earlier but marked as deprecated for now, let's check back when we clean up def visualize(self, plt=None): raise NotImplementedError("Unimplemented abstract base method") def reset(self, randomize=0): """ Resets vehicle to its original (intitialized) location-heading and sets velocity and accel to 0 :param randomize: if set to True, x-y placement will randomized and won't be exactly the original x-y """ if randomize > 0: x, y, theta = self._initial_pose # this is in projected meters rnd = random.uniform(-randomize, randomize) x += rnd rnd = random.uniform(-randomize, randomize) y += rnd # as of now, we don't need theta noise/randomization here, it is handled in the simulator self._pose = np.array([x, y, theta]) else: # else, no randomize, just place back to original self._pose = self._initial_pose self._velocity = 0.0 self._acceleration = 0.0 def set(self, x, y, theta, randomize=0): """ Sets vehicle to a location-heading and sets velocity and accel to 0 Similar to reset as it will zero out accel and velocity but you can provide an arbitrary location :param x: X coord in meters :param y: Y coord in meters :param theta: heading andle in radians """ self._velocity = 0.0 self._acceleration = 0.0 rnd = random.uniform(-randomize, randomize) x += rnd rnd = random.uniform(-randomize, randomize) y += rnd self._pose = np.array([x, y, theta % (2 * pi)]) @abstractmethod def get_info_object(self): raise NotImplementedError("Unimplemented abstract base method") #endregion #region Protected methods @abstractmethod def _set_pose(self, x, y, theta): raise NotImplementedError("Unimplemented abstract base method") #@abstractmethod # TODO we used this earlier but marked as deprecated for now, let's check back when we clean up def _update_pose(self, x, y, theta): raise NotImplementedError("Unimplemented abstract base method") #endregion class PointModel(IVehicleModel): def __init__(self, x, y, theta=0.0, max_velocity=0.5, max_accel=0.1, vehicle_id="Point model", noise=0, **kwargs): super().__init__(x, y, theta, vehicle_id=vehicle_id) # private members self._max_velocity = max_velocity self._max_accel = max_accel self._noise = noise self._previous_theta = theta % (pi * 2) self._pose = np.array([x, y, theta % (pi * 2)]) # construct visual representation of model self._sprite = (200, pygame.Surface((1000, 1000), pygame.SRCALPHA, 32)) car_corners = [(500, 240), (620, 760), (380, 760)] pygame.draw.aalines(self._sprite[1], (0, 0, 0), True, car_corners) pygame.draw.polygon(self._sprite[1], (0, 0, 0), car_corners) @property def pose(self): """ Center of mass pose: [x, y, theta] :return: The raw pose np.array in x-y-theta format (where x-y is projected lat-lon in meters, Japan projection) """ return self._pose @property def position(self): """ Center of mass position: [x, y] :return: The raw position np.array in projected x-y format (meters, Japan projection) """ return self._pose[0:2] @property def orientation(self): """ Center of mass orientation: theta """ return self._pose[2] @property def velocity(self): """ Vehicle velocity """ return self._velocity @property def acceleration(self): """ Vehicle acceleration (speed diference in the previous two steps) """ return self._acceleration @property def max_accel(self): """ Maximum acceleration. """ return self._max_accel @property def max_velocity(self): """ Maximum speed. """ return self._max_velocity @property def angular_velocity(self): """ The angular velocity based on the last movement (change of orientation/heading between steps since we operate step-based). :returns: a velocity value (angle/step) """ return self.orientation - self._previous_theta @property def sprite(self): """Get the visual representation of the model.""" return self._sprite #region Public methods def move_accel(self, a=None, theta=None): """ Acceleration-based step simulation. Vehicle will move forward based on the input parameters (and its internal constraints) :param a: acceleration with which the model should move :param theta: angle in which direction the model should move :return: None """ if a is None: a = self.acceleration LOGGER.debug("No acceleration provided, keeping previous value") elif self.max_accel is not None: # else constrain it to be within the specified min-max a = np.clip(a, -self.max_accel, self.max_accel) if theta is None: theta = self.orientation LOGGER.debug("No steer angle provided, keeping previous value") v = self.velocity + a # generate noise rand_v = random.uniform(v * (-self._noise / 100), v * (self._noise / 100)) rand_t = random.uniform(theta * (-self._noise / 10000), theta * (self._noise / 10000)) LOGGER.debug("noise values: v: {0} t: {1}".format(rand_v, rand_t)) v += rand_v theta += rand_t # only constrain velocity if there is a max value specified if self.max_velocity is not None: v = np.clip(v, 0, self.max_velocity) # use geoutils to calculate new position new_x, new_y = offset(self._pose, v, theta) # set new pose self._set_pose(new_x, new_y, theta) # accel = new velo - old velo # don't use the user supported one in the params as it might be larger than the limit! self._acceleration = v - self._velocity # save new velo self._velocity = v def move_velocity(self, v, theta=None): """ Velocity-based step simulation. Vehicle will move forward based on the input parameters (and its internal constraints) :param v: velocity/speed with which the model should move :param theta: angle in which direction the model should move :return: None """ accel = v - self.velocity self.move_accel(accel, theta) def get_info_object(self): car_info_object = { "car_model": "Point", "object_type": "car", "car_position_x": self.position[0], "car_position_y": self.position[1], "car_direction": self.orientation, "car_speed": self.velocity, "car_accel": self.acceleration, "max_speed": self.max_velocity, "max_accel": self.max_accel, } return car_info_object #endregion #region Private methods def _set_pose(self, x, y, theta): """ Sets (saves) a new pose. :param x: new x position (in meters, projected) :param y: new y position (in meters, projected) :param theta: new heading (angle) :return: None """ # save old pose so we can calculate speed and accel prev = self._pose # constrain theta onto [0..2*pi] if theta < 0: new_theta = theta % (2 * pi) LOGGER.debug("Converting {} degrees to {} degrees.".format(theta, new_theta)) theta = new_theta elif theta > 2 * pi: new_theta = theta % (2 * pi) LOGGER.debug("Converting {} degrees to {} degrees.".format(theta, new_theta)) theta = new_theta self._previous_theta = self.orientation self._pose = np.array([x, y, theta]) LOGGER.debug("Vehicle pose set " + str(self)) #endregion class BicycleModel(PointModel): """ Represents one instance of the bicycle model. Holds its state variables and capable to execute its actions. It inherits a lot of functionalities from the simpler PointModel. """ # Toyota Corolla has 2.6m wheelbase # 50 m/s max speed = 180 kmph # WGS84 is in meters, let's keep use meters for now def __init__( self, x, y, theta=0.0, wheelbase=2.6, track=1.2, max_wheel_angle=pi / 3, # 60 degrees max_velocity=0.5, max_accel=0.1, vehicle_id="Bicycle model", noise=0): super().__init__(x, y, theta, vehicle_id=vehicle_id, max_velocity=max_velocity, max_accel=max_accel) # private members self._wheelbase = wheelbase self._track = track self._max_wheel_angle = max_wheel_angle % pi self._wheel_turn_angle = 0.0 self._noise = noise self._previous_wheel_angle = 0.0 LOGGER.info("===== Bicycle vehicle model initialized with the following parameters ====") LOGGER.info(self) #region Properties @property def wheelbase(self): """Get the length of the vehicle in meters (wheelbase)""" return self._wheelbase @property def track(self): """Get the width of the vehicle in meters (track)""" return self._track @property def wheel_turn_angle(self): """ Current wheel turn angle :returns: the current wheel turn angle (in degrees, a value between -max_wheel_angle...max_vmax_wheel_angle) """ return self._wheel_turn_angle @property def max_wheel_angle(self): """ The max wheel angle - since the wheel is symmetric, the min wheel angle is just -max_wheel_angle. :returns: the current max wheel angle """ return self._max_wheel_angle @property def turn_radius(self): """ Current turn radius based on the current wheel turn angle :returns: a radius in meters. None if we are not turning, be sure to handle corner case. """ if self.wheel_turn_angle is None or self.wheel_turn_angle == 0.0: return None return self._wheelbase / tan(self.wheel_turn_angle) @property def wheel_angle_change(self): """ The difference between the current and last recorded wheel angles :returns: the cange value in degrees (signed) """ return self._wheel_turn_angle - self._previous_wheel_angle @property def center_of_turn(self): """ The coordinate of the point we are turning around (i.e. the center of the circle along which we are turning) :returns: an x-y coordinate pair. None if we are not turning, be sure to handle corner case. """ if self._wheel_turn_angle == 0.0: return None x, y, theta = self.pose x_center = x + self.turn_radius * cos(theta) y_center = y - self.turn_radius * sin(theta) return (x_center, y_center) @property def radial_speed(self): """ The sideways component of our speed vector :returns: a velocity value (meters / step) """ return self.velocity * sin(self.orientation) @property def cross_radial_speed(self): """ The forward component of our speed vector (along the axis of the vehicle) :returns: a velocity value (meters / step) """ return self.velocity * cos(self.orientation) @property def sprite(self): """Get the visual representation of the model.""" return self._sprite #endregion #region IVehicleModel implementation def move_accel(self, a=None, wheel_angle=None): """ Acceleration-based step simulation. Vehicle will move forward based on the input parameters (and its internal constraints) :param a: acceleration with which the model should move :param wheel_angle: angle in which direction the wheel should be turned before movement :return: None """ if a is None: a = self.acceleration LOGGER.debug("No acceleration provided, keeping previous value: %f", self.acceleration) elif self.max_accel is not None: # else constrain it to be within the specified min-max a = np.clip(a, -self.max_accel, self.max_accel) if wheel_angle is None: wheel_angle = self.wheel_turn_angle LOGGER.debug("No steer angle provided, keeping previous value: %f", self.wheel_turn_angle) elif self._max_wheel_angle is not None: # constrain angle within allowed boundaries wheel_angle = np.clip(wheel_angle, -self._max_wheel_angle, self._max_wheel_angle) # generate noise on the inputted control parameters rand_accel = random.uniform(a * (-self._noise / 100), a * (self._noise / 100)) rand_wheel_angle = random.uniform(wheel_angle * (-self._noise / 100), wheel_angle * (self._noise / 100)) LOGGER.debug("Added action noise values: acceleration: {0} wheel_angle: {1}".format( rand_accel, rand_wheel_angle)) # add generated noise (it'll be 0 if noise is set to 0) a += rand_accel wheel_angle += rand_wheel_angle self._previous_wheel_angle = self._wheel_turn_angle self._wheel_turn_angle = wheel_angle v = self.velocity + a # constrain velocity within allowed boundaries if self.max_velocity is not None: v = np.clip(v, 0, self.max_velocity) # calculate the changes in position and heading # v is the distance traveled by the rear wheel during this step if self.turn_radius is not None: beta = v / self.turn_radius theta = self.orientation + beta else: theta = self.orientation if self.center_of_turn is None: # just move forward # use geoutils to do the straight line movement x_prime, y_prime = offset(self.position, v, theta) else: xc, yc = self.center_of_turn x_prime = xc - self.turn_radius * cos(theta) y_prime = yc + self.turn_radius * sin(theta) # set new pose self._set_pose(x_prime, y_prime, theta) # accel = new velo - old velo # don't use the user supported one in the params as it might be larger than the limit! self._acceleration = v - self._velocity # save new velo self._velocity = v def move_velocity(self, v, wheel_angle=None): """ Velocity-based step simulation. Vehicle will move forward based on the input parameters (and its internal constraints) The implementation is the same as in the parent but reimplemented since the angle represents something else here :param v: velocity/speed with which the model should move :param wheel_angle: angle in which direction the wheels should point [-max_angle .. max_angle] :return: None """ accel = v - self.velocity self.move_accel(accel, wheel_angle) def get_info_object(self): car_info_object = { "car_model": "Bicycle", "object_type": "car", "car_position_x": self.position[0], "car_position_y": self.position[1], "car_direction": self.orientation, "steering_angle": self.wheel_turn_angle, "car_speed": self.velocity, "car_accel": self.acceleration, "max_wheel_angle": self.max_wheel_angle, "max_speed": self.max_velocity, "max_accel": self.max_accel, "wheelbase": self.wheelbase } return car_info_object #endregion
249dec61532df6607163bb945469ddc0e6a731bd
architsangal/Python_Assignments
/a2/Q6b.py
409
3.53125
4
from Q6input import * # Your code - begin for i in range(0,len(l)-1):# for different passes... last pass is not required so it is len(l)-1 for j in range(i+1,len(l)):# loop from next element till end if(l[i]>l[j]): temp=l[i] l[i]=l[j] l[j]=temp median=0 if(len(l)%2==1): median=l[(len(l)-1)/2] else: median=(l[(len(l)-2)/2]+float(l[len(l)/2]))/2; output=median # Your code - end print output
396da8ac3bc4a90525339ca352556115219d9152
yazfir/Projects2021
/PythonCardio/conversor.py
1,572
4.125
4
""" Reto 3 - Conversor de millas a kilómetros Imagina que quieres calcular los kilómetros que son cierta cantidad de millas. Para no estar repitiendo este cálculo escribe un programa en que el usuario indique una cantidad de millas y en pantalla se muestre el resultado convertido a kilómetros. Toma en cuenta que en cada milla hay 1.609344 Km Bonus: haz que el usuario pueda escoger entre convertir millas a kilómetros o kilómetros a millas. """ import os def clear(): os.system('clear') def km_to_mis(longitud): #Convierte Km a Millas return longitud * 0.621371 def mis_to_km(longitud): #Convierte Millas a Km return longitud / 0.621371 def main(): clear() print('**** Convertidor de KMs a Millas y Millas a KMs **** \n') while True: try: tipo_conversor = int(input('Ingrese 1 - KM a MIS 2 - MIS a KM. Otro número para terminar: >> ')) if tipo_conversor == 1: unidades = float(input('\nIndica las unidades a convertir: >> ')) print(f'\n{ str(unidades) } km a millas son: { str(km_to_mis(unidades)) } millas\n\n') elif tipo_conversor == 2: unidades = float(input('\nIndica las unidades a convertir: >> ')) print(f'\n{ str(unidades) } millas a km son: { str(mis_to_km(unidades)) } km\n\n') else: break; except: print('Valor incorrecto. Vuelva a ingresar datos.\n') continue if __name__ == "__main__": main()
60b563fba42cf731768aa62c235b9dcb579cfd55
yyk752122/nanjing_yidong
/demo.py
207
3.71875
4
a = {"peple":{"set":{"name":"xiaohua","age":"18"},"set1":{"name":"xiaoming","age":"22"}}} b = a["peple"] # print(b) print(b) c= list() print(b.values()) # for i in b.values(): # c.append(i) # print(c)
a448b375e5889a9c2e1ed298d67f3b9eb395d910
AnishDeshpande1/AI-ML
/lab2-180100013/utils.py
5,974
3.921875
4
import numpy as np def load_data1(file): ''' Given a file, this function returns X, the regression features and Y, the output Args: filename - is a csv file with the format feature1,feature2, ... featureN,y 0.12,0.31,1.33, ... ,5.32 Returns: X - numpy array of shape (number of samples, number of features) Y - numpy array of shape (number of samples, 1) ''' data = np.loadtxt(file, delimiter=',', skiprows=1) X = data[:, :-1] Y = data[:, -1:] return X, Y def load_data2(file): ''' Given a file, this function returns X, the features and Y, the output Args: filename - is a csv file with the format feature1,feature2, ... featureN,y 0.12,0.31,Yes, ... ,5.32 Returns: X - numpy array of shape (number of samples, number of features) Y - numpy array of shape (number of samples, 1) ''' data = np.loadtxt(file, delimiter=',', skiprows=1, dtype='str') X = data[:, :-1] Y = data[:, -1:].astype(float) return X, Y def split_data(X, Y, train_ratio=0.8): ''' Split data into train and test sets The first floor(train_ratio*n_sample) samples form the train set and the remaining the test set Args: X - numpy array of shape (n_samples, n_features) Y - numpy array of shape (n_samples, 1) train_ratio - fraction of samples to be used as training data Returns: X_train, Y_train, X_test, Y_test ''' ## TODO X_train = [] Y_train = [] X_test = [] Y_test = [] # test_seq = [] # N = np.shape(X)[0] # train_len = int(np.floor(N * train_ratio)) # random_seq = np.random.choice(N, train_len, replace=False) # test_seq_encode = np.zeros(N) # for a in random_seq: # X_train.append(X[a]) # Y_train.append(Y[a]) # test_seq_encode[a] = 1 # for i in range(0,N): # if test_seq_encode[i] == 0: # test_seq.append(i) # for a in test_seq: # X_test.append(X[a]) # Y_test.append(Y[a]) # X_train = np.array(X_train) # X_test = np.array(X_test) # Y_train = np.array(Y_train) # Y_test = np.array(Y_test) N = np.shape(X)[0] train_len = int(np.floor(N * train_ratio)) for i in range(N): if(i<train_len): X_train.append(X[i]) Y_train.append(Y[i]) else: X_test.append(X[i]) Y_test.append(Y[i]) ## END TODO return X_train, Y_train, X_test, Y_test def one_hot_encode(X, labels): ''' Args: X - numpy array of shape (n_samples, 1) labels - list of all possible labels for current category Returns: X in one hot encoded format (numpy array of shape (n_samples, n_labels)) ''' X.shape = (X.shape[0], 1) newX = np.zeros((X.shape[0], len(labels))) label_encoding = {} for i, l in enumerate(labels): label_encoding[l] = i for i in range(X.shape[0]): newX[i, label_encoding[X[i,0]]] = 1 return newX def normalize(X): ''' Returns normalized X Args: X of shape (n_samples, 1) Returns: (X - mean(X))/std(X) ''' ## TODO # n_samples = np.shape(X)[0] # mean = 0.0 # for i in range(n_samples): # mean = mean+float(X[i]) # mean = mean / n_samples # # X = np.array(X) # # print(X) # # print(np.char.isnumeric(X)) # # mean = np.mean(X) # std = 0.0 # for i in range(n_samples): # std = std + (float(X[i])-mean)**2 # std = std**0.5 # #std = np.std(X) # for i in range(np.shape(X)[0]): # X[i] = (float(X[i])-mean)/std # X = np.array([float(x) for x in X]) Y = np.zeros((np.shape(X)[0],1)) for i in range(np.shape(X)[0]): Y[i]=float(X[i]) Y = Y - np.mean(Y) Y = Y/np.std(Y) return Y ## END TODO def preprocess(X, Y): ''' X - feature matrix; numpy array of shape (n_samples, n_features) Y - outputs; numpy array of shape (n_samples, 1) Convert data X obtained from load_data2 to a usable format by gradient descent function Use one_hot_encode() to convert NOTE 1: X has first column denote index of data point. Ignore that column and add constant 1 instead (for bias) NOTE 2: For categorical string data, encode using one_hot_encode() and normalize the other features and Y using normalize() ''' ## TODO # final_X = [] # for i in range(np.shape(X)[0]): # X[i][0]=1 # #print(X) # temp = X[:,0] # final_X.append(temp) # for i in range(1,np.shape(X)[1]): # X_num = np.char.isnumeric(X[:,i]) # flag = False # for j in range(np.shape(X)[0]): # if X_num[i] == False: # flag = True # break # if flag: # label = [] # for j in range(np.shape(X)[0]): # if X[j,i] not in label: # label.append(X[j,i]) # new_X = one_hot_encode(X[:,i], label) # for cols in new_X: # final_X.append(cols) # else: # new_X = normalize(X[:,i]) # final_X.append(new_X) # #Y = normalize(Y) # #print(final_X) # final_X = np.transpose(final_X) # fin = pd.DataFrame(final_X) # print(fin.head()) n_samples = np.shape(X)[0] n_features = np.shape(X)[1] num_cols_to_add = 0 categorical_cols = [] for i in range(n_features): # X_num = np.char.isnumeric(np.array(X[:,i])) # flag = False # for j in range(n_samples): # if X_num[j] == False: # flag = True # break flag = False for j in range(n_samples): try: val = int(X[j,i]) except: flag = True break if flag: categorical_cols.append(i) label = [] for j in range(n_samples): if X[j,i] not in label: label.append(X[j,i]) t = len(label) num_cols_to_add = num_cols_to_add + t - 1 final_X = np.zeros((n_samples,n_features+num_cols_to_add)) col_pointer = 1 final_X[:,0] = 1.0 for i in range(1,n_features): if i not in categorical_cols: temp = normalize(X[:,i]) for j in range(n_samples): final_X[j][col_pointer]=float(temp[j]) col_pointer=col_pointer+1 else: label = [] for j in range(n_samples): if X[j][i] not in label: label.append(X[j][i]) new_X = one_hot_encode(X[:,i], label) for k in range(len(label)): for p in range(n_samples): final_X[p][col_pointer]=float(new_X[p][k]) col_pointer = col_pointer + 1 #print(final_X.shape) Y = normalize(Y) return final_X,Y ## END TODO
7d9e8d5de58c4e833f651172a6b7126c2b492942
ajc327/Genetic_Algorithm_Solver
/build/lib/ga_module/ga_settings.py
1,869
3.546875
4
# Created by Andy at 03-Jan-21 # Enter description here # ___________________________________ from abc import ABC, abstractmethod class Validator(ABC): def __set_name__(self, owner, name): self.private_name = "_"+ name def __get__(self, obj, objtype = None): return getattr(obj, self.private_name) def __set__(self, obj, value): self.validate(value) return setattr(obj, self.private_name, value) @abstractmethod def validate(self, value): pass class Number(Validator): def __init__(self, min_value = None, max_value = None, isint = False): self.min_value = min_value self.max_value = max_value self.is_int = isint def validate(self, value): if self.is_int and not isinstance(value, int): raise TypeError(f"Expected {value!r} to be an inteter") if not isinstance(value, (int,float)): raise TypeError(f"Expected {value!r} to be a float or an integer") if self.min_value is not None and value<self.min_value: raise ValueError(f"Expected value to be at least {self.min_value}") elif self.max_value is not None and value > self.max_value: raise ValueError(f"Expected {value} to be at most {self.max_value}") class Settings(): '''Settings object for the solver''' population_size = Number(1,1000, True) p_cross = Number(0,1) p_mutation = Number(0,1) def __init__(self, population_size=50, p_mutation=0.01, p_cross=0.5): self.population_size = int(population_size) self.p_mutation = p_mutation self.p_cross = p_cross self.mutator = None self.selector = None if __name__ == "__main__": test_settings = Settings(population_size=50, p_mutation=-0.1, p_cross=-0.2) print(test_settings.p_cross)
9c1312ccfd1106416c5dd25e089d2a5df8a2f85c
kukukuni/Python_ex
/2day/List02.py
378
3.8125
4
# List02.py a = [10,20,30] print(len(a),a) a.append(40) print(len(a),a) a.append(20) print(len(a),a,a.count(20)) a.insert(1,50) print(len(a),a) a.pop() print(len(a),a) a.pop(1) print(len(a),a) a.remove(20) print(len(a),a) a += [20] print(len(a),a) a.extend([50,60]) print(len(a),a) a += [70, 80] print(len(a),a) print(a.index(20)) a.pop(-3) print(len(a),a)
74b891813fe28793b4c3cae0575342ad574ccf54
andaro07/andaro07
/even_numbers.py
206
3.828125
4
l = int(input('Enter lower limit of the range: ')) u = int(input('Enter upper limit of the range: ')) a = [] for i in range(l, u+1): if i % 2 == 0: a.append(i) print('The even numbers are {}'.format(a))
b5a59e1354e6ff754a2a854be50df059f226a5ca
parkerahall/dailycodingchallenge
/5-30-19.py
3,023
4.0625
4
from linked_list import SinglyLinkedList def find_length(linked_list): length = 0 curr = linked_list while curr != None: curr = curr.next length += 1 return length # used for debugging def print_length(head, length): l = [] while head != None and length > 0: l.append(head.value) head = head.next length -= 1 print(l) def merge_portion(prev, head, length): first_head = head second_head = head for _ in range(length / 2): second_head = second_head.next last_last = head for _ in range(length): last_last = last_last.next first_moves = 0 second_moves = 0 new_head = None curr = new_head while first_moves + second_moves < length: if first_moves == length / 2: curr.next = second_head second_moves = length / 2 elif second_moves == length / 2: curr.next = first_head first_moves = length / 2 elif first_head.value < second_head.value: if new_head == None: new_head = first_head curr = first_head else: curr.next = first_head curr = curr.next first_head = first_head.next first_moves += 1 else: if new_head == None: new_head = second_head curr = second_head else: curr.next = second_head curr = curr.next second_head = second_head.next second_moves += 1 if prev != None: prev.next = new_head last = new_head for _ in range(length - 1): last = last.next return new_head, last, last_last # assumes length of linked_list is a power of 2 def merge_sort(head): n = find_length(head) curr = head length = 2 while length <= n: prev = None new_head = None for _ in range(n / length): portion_head, prev, curr = merge_portion(prev, curr, length) if new_head == None: new_head = portion_head prev.next = None curr = new_head length *= 2 return curr head = SinglyLinkedList(4, nxt=SinglyLinkedList(1, nxt=SinglyLinkedList(3, nxt=SinglyLinkedList(99)))) expected = head = SinglyLinkedList(1, nxt=SinglyLinkedList(3, nxt=SinglyLinkedList(4, nxt=SinglyLinkedList(99)))) actual = merge_sort(head) assert actual == expected second_half = SinglyLinkedList(4, nxt=SinglyLinkedList(1, nxt=SinglyLinkedList(3, nxt=SinglyLinkedList(99)))) head = SinglyLinkedList(101, nxt=SinglyLinkedList(-1, nxt=SinglyLinkedList(-7, nxt=SinglyLinkedList(2, nxt=second_half)))) second_expected = SinglyLinkedList(3, nxt=SinglyLinkedList(4, nxt=SinglyLinkedList(99, nxt=SinglyLinkedList(101)))) expected = SinglyLinkedList(-7, nxt=SinglyLinkedList(-1, nxt=SinglyLinkedList(1, nxt=SinglyLinkedList(2, nxt=second_expected)))) actual = merge_sort(head) assert actual == expected
21abffa0e0eb326be8b81fcd9f1890c814cc9937
aashishbiradar/data-structures-in-python
/linked-list/linked-list.py
737
4.0625
4
# Node Class class Node: def __init__(self, data = None): self.data = data self.next = None # Linked list Class class LinkedList: def __init__(self, arr): self.head = head = Node(arr[0]) for i in range(1,len(arr)): head.next = Node(arr[i]) head = head.next # Code execution starts here if __name__=='__main__': print('<== START ==>') arr = [1,2,3,4,5] print('Data Array', arr) print('inserting into/ creating a linked list from data array') llist = LinkedList(arr) # traversing linked list print('traversing linked list') head = llist.head while head: print(head.data) head = head.next print('<== END ==>')
81ef5f5c8f1841aaba36614b3713f394213f138e
SwathiChennamaneni/repo1
/Assignments/Assignment_60/Operations_CSV_File.py
3,318
4.1875
4
"""60. Show the below menu to the user: 1. Add a row 2. modify a row 3. delete a row Go with one unique field in the file. And maintain that unique constraint in all file modifiction operations Use .CSV file for this program""" import random import os import sys select = True while select: print "\n***** Menu *****" print "1. Add a Row\n2. Modify a Row\n3. Delete a Row\n4. Quit" select = raw_input("\nSelect:") if not os.path.exists("D:\py_programs\Assignments\Assignment_60\csv1_op.csv"): columns=['Id','Name','Age','Class','Rank'] f = open("csv1_op.csv","w") rows=[] rows.insert(0,",".join(columns)+"\n") f.writelines(rows) f.close() last = 1 else: t_d = open("csv1_op.csv","r").readlines() count = len(t_d[1:]) if count: last = int(t_d[count][0]) + 1 else: last = 1 if select == '1' : #ID = last + int(1) Name = raw_input("Enter Name:") Age=raw_input("Enter Age:") Class = raw_input("Enter Class:") Rank = raw_input("Enter Rank:") rows=[] f = open("csv1_op.csv","a") row = "{0},{1},{2},{3},{4}\n".format(last,Name,Age,Class,Rank) rows.append(row) f.writelines(rows) print "Added Students Info in to a Row" print "Row/Student Id is:",last f.close() elif select == '2': ID = raw_input("Enter ID:") t_d = open("csv1_op.csv","r").readlines() for row in t_d[2:]: each_row = row.split(',') if str(ID) == row.split(',')[0]: req_row = row #print req_row ind = t_d.index(req_row) req_row = row.split(',') print "Current Available Info:", req_row Name = raw_input("Enter Name[{0}]:".format(req_row[1])) Age = raw_input("Enter Age [{0}]:".format(req_row[2])) Class = raw_input("Enter Class[{0}]:".format(req_row[3])) Rank = raw_input("Enter Rank[{0}]:".format(req_row[4].strip('\n'))) if Name == '': Name = row.split(',')[1] if Age == '': Age = row.split(',')[2] if Class == '': Class = row.split(',')[3] if Rank =='': Rank = row.split(',')[4] row ="{0},{1},{2},{3},{4}\n".format(ID,Name,Age,Class,Rank) t_d[ind] = row f = open("csv1_op.csv","w") f.writelines(t_d) f.close() print "\nModified Row/Student Information .." elif select == '3' : flag=True ID = raw_input("Enter ID of Employee:") t_d = open("csv1_op.csv","r").readlines() count1 = len(t_d) for row in t_d: if str(ID) == row.split(',')[0]: print "Row:",row t_d.remove(row) f = open("csv1_op.csv","w") f.writelines(t_d) f.close() print "Deleted Students Information" elif select == '4': print "\nYou have Selected to Exit.." break else: print "\nSelect Appropriate Option\n"
feaf1282af740767ea4e3f3d4800be373f018fda
SichaoLiuKTH/static-gesture-recognition
/states.py
2,862
4.0625
4
import time, sys, os # Print function to get right indents def printout(self, toPrint): sys.stdout.write("\r {:<50s}".format(toPrint)) printCart(self.cart) # Print what is in the cart def printCart(cart): print("{:>50}{}".format('Cart: ', ', '.join(cart))) ''' Gstate contains the state in the program flow and the cart. It also contains the main UI progrm flow function, GestureState. ''' class Gstate: current_state = 0 cart = [] gestures = {0: 'INIT', 1: 'ALCOHOL', 2: 'NON-ALCOHOL', 3:'FOOD', 4: 'UNDO', 5:'CHECKOUT', 6:'CASH', 7:'CREDIT CARD'} ''' GestureState is the UI and main program flow. Input arguments: class state and gesture as int in the range [0, 7] ''' def GestureState(self, gesture): if gesture == 0 and self.current_state == 0: self.current_state = 1 os.system("say 'What would you like to order?'") printout(self, "What would you like to order?") elif gesture == 1 and self.current_state == 1: self.cart.append(self.gestures[gesture]) os.system("say 'Alcoholic drink added!'") printout(self, "Alcoholic drink added!") elif gesture == 2 and self.current_state == 1: self.cart.append(self.gestures[gesture]) os.system("say 'Non-alcohol drink added!'") printout(self, "Non-alcohol drink added!") elif gesture == 3 and self.current_state == 1: os.system("say 'Food added!'") self.cart.append(self.gestures[gesture]) printout(self, "{} added.".format(self.gestures[gesture])) elif gesture == 4 and self.current_state == 1 and len(self.cart) > 0: removedItem = self.cart[len(self.cart)-1] os.system("say 'Undoing!'") self.cart.pop() printout(self, "Removed {} from cart".format(removedItem)) elif gesture == 4 and self.current_state == 1 and len(self.cart) == 0: self.current_state = 0 os.system("say 'Nothing more to remove, going back. Welcome back'") printout(self, "Nothing more to remove, going back....... Welcome back") elif gesture == 5 and self.current_state == 1: self.current_state = 2 os.system("say 'How would you like to pay?'") printout(self, "How would you like to pay?") elif gesture == 6 and self.current_state == 2: os.system("say 'You paid with cash, cash is king!'") printout(self, "You paid for {} and payed with {}".format(", ".join(self.cart), self.gestures[gesture])) self.cart = [] self.current_state = 0 return 99 elif gesture == 7 and self.current_state == 2: os.system("say 'You paid with card!'") printout(self, "You paid for {} and payed with {}".format(", ".join(self.cart), self.gestures[gesture])) self.cart = [] self.current_state = 0 return 99 elif gesture == 5 and self.current_state == 2: self.current_state = 1 os.system("say 'Back to order'") printout(self, "Back to order!")
11e351cfa9e57928182f9b82796698861151880a
PrimesInterPares/SK
/General Instructions/rand_frequency.py
361
3.734375
4
# -*- coding: utf-8 -*- from random import randint n = input(u'Input number : ') randomNumbers = [] count = 0. for i in range(n): randomNumbers.append(randint(1,6)) if randomNumbers[i] == 6: count += 1 chance = count/n print "Count of 6 : %.f" %(count) print "Chance of 6's precipitation : %.3f" %(chance) print randomNumbers
4ed8885a8cca99d6dd98ee67a7d6603227218977
tooooo1/CodeUp
/basic100/basic_level_4-1/1076.py
93
3.546875
4
x = input() num = ord(x) for y in range(97, num+1): print(chr(y), end=' ') num -= 1
7c5281274c470eb1fff766d3f5137f8b7a79c2d5
ww35133634/chenxusheng
/ITcoach/算法+数据结构/程序设计/设计模式/设计模式/strategy.py
834
3.59375
4
# coding: utf-8 # author: ztypl # date: 2018/12/27 from abc import ABCMeta,abstractmethod class Strategy(metaclass=ABCMeta): @abstractmethod def execute(self, data): pass class FastStrategy(Strategy): def execute(self, data): print("用较快的策略处理%s" % data) class SlowStrategy(Strategy): def execute(self, data): print("用较慢的策略处理%s" % data) class Context: def __init__(self, strategy, data): self.data = data self.strategy = strategy def set_strategy(self, strategy): self.strategy = strategy def do_strategy(self): self.strategy.execute(self.data) # Client data = "[...]" s1 = FastStrategy() s2 = SlowStrategy() context = Context(s1, data) context.do_strategy() context.set_strategy(s2) context.do_strategy()
0950c8c75b2e012cc98ffa22a3b5c029e08fc697
KietLyanh/pp2021
/Labwork 4/output.py
328
3.734375
4
print("Welcome to student mark management program") print("What do you want to do") print("1. Add student") print("2. Add course") print("3. Calculate GPA") options = int(input("Choose option: ")) if options == 1: addStudent() elif options == 2: addCourse() elif options == 3: caculateGPA() else: print("Error")
b63ad15c7cc6017da6537a668dd4aec540fc0641
MartinCarli/LB-F1
/e5.py
4,382
3.828125
4
#c e qualche problema con l ultima parte, RICONTROLLA # #Creo una classe automobile class Automobile: #Definisco la mia classe con i suoi attributi def __init__(self, casa_auto, modello, numero_posti, numero_portiere, kw, targa): self.casa_auto=casa_auto self.modello=modello self.numero_posti=numero_posti self.numero_portiere=numero_portiere self.kw=kw self.targa=targa #stampo le caratteristiche delle automobili presenti nella classe def __str__(self): return' {} {} {} {} {} {}'.format(self.casa_auto, self.modello, self.numero_posti, self.numero_portiere, self.kw, self.targa) #stampo 'Broom Broom' tramite la creazione della funzione parla def parla(self): print('Broom Broom') #TESTO ESERCIZIO:confronta, metodo che, dato in ingresso self e un’altra #istanza di Automobile, determina se le due automobili hanno le stesse informazioni #(eccetto per la targa che `e univoca!). #confronto se le auto hanno caratteristiche uguali def confronta(self, a ):#a corrisponde ad automobile2 #casa_auto if (self.casa_auto==a.casa_auto): print('= casa') else: print('!= casa') print('.................................................') #modello if (self.modello==a.modello): print('= modello') else: print('!= modello') print('.................................................') #numero_posti if(self.numero_posti==a.numero_posti): print('= numero di posti') else: print('!= numero di posti') print('.................................................') #numero_portiere if(self.numero_portiere==a.numero_portiere): print('= numero portiere') else: print('!= numero portiere') print('.................................................') #kw if (self.kw==a.kw): print('= kw') else: print('!= kw') print('.................................................') #considero il bollo per le diverse auto def bollo(self, cat): if (cat=='Euro0'): if (self.kw<100): print('Euro0 con kw<100, bollo:',self.kw*3) else: print('Euro0 con kw>100, bollo:', self.kw*4.50) elif (cat=='Euro1'): if (self.kw<100): print('Euro1 con kw<100, bollo:',self.kw*2.50) else: print('Euro1 con kw>100, bollo:', self.kw*4.35) else: print('Euro2, bollo:', self.kw*2) automobile1=Automobile(casa_auto='Fiat', modello='600', numero_posti=4, numero_portiere=3, kw=56, targa='AB456CD') automobile2=Automobile(casa_auto='Fiat', modello='Panda', numero_posti=5, numero_portiere=5, kw=69, targa='CD456AB') automobile3=Automobile(casa_auto='Audi', modello='A1', numero_posti=5, numero_portiere=5, kw=90, targa='FP364UZ') print('\t') print('automobile1:') print(automobile1) print('automobile2:') print(automobile2) print('automobile3:') print(automobile3) print('\t') automobile1.parla() print('\t') print('CONFR. AUTOMOBILE1 CON AUTOMOBILE2') print(Automobile.confronta(automobile1, automobile2)) print('\t') print('CONFR. AUTOMOBILE2 CON AUTOMOBILE3') print(Automobile.confronta(automobile2, automobile3)) print('\t') print(automobile1.bollo('Euro0')) class Trasformers(Automobile): def __init__(self,nome, generazione, grado, fazione, reparto): super().__init__("Trasformers", casa_auto, modello, numero_posti, numero_portiere, kw, targa) self.nome=nome self.generazione=generazione self.grado=grado self.fazione=fazione self.reparto=reparto def parla (self, a):#a trasformers2 if self.fazione=='Autobot': print('Noi siamo Autobots, proteggeremo ogni essere vivente') else: print('Noi siamo Decepticons e l AllSpark sarà nostro!') trasformers1=Trasformers(nome='Trasformers', generazione='1', grado='soldato semplice', fazione='Autobot', reparto='corpo a corpo') trasformers2=Trasformers(nome='Trasformers', generazione='2', grado='sergente', fazione='Decepticon', reparto='atiglieria leggera') Trasformers.parla(trasformers1, trasformers2)
e6c3613c741368dce03b96b8ae47a4c5ed5e2210
samiran163/Helloworld
/Samiran.py
509
4.28125
4
# Arithmetic operator num1 = 10 num2 = 20 num3 = 3 num4 = 7 print("Num1 + Num2 =", num1 + num2) print("Num1 - Num2 =", num1 - num2) print("Num1 * Num2 =", num1 * num2) print("Num2 / Num2 =", num2 / num1) print("Num4 % Num3 =", num4 % num3) print("Num4 // Num3 =", num4 // num3) print("Num4 ^ Num3 =", num4 ** num3) # Assignment operator num5 = num1 + num2 print("Value =",num5) num5 += num2 # num5 = num5 + num2 print("Value_2=", num5) # Comparison operator # Logical operators
1240f3641e57b25860b2547e980bc88158f24e41
eestey/PRG105-StringPractice
/String Practice.py
1,371
4.34375
4
# Print the first letter of the following string school = "McHenry County College" letter = school[0] print letter # print the length of the school string school = "McHenry County College" len(school) print len(school) # Use a while loop to print each character (including spaces) in the school variable index = 0 while index < len(school): letter = school[index] print letter index += 1 # Slice school into three variables, print the variables school = "McHenry County College" print school[0:7] print school[8:14] print school[15:22] # use a while statement to search for the letter "e" in the contents of the school variable # print the index of every location with the letter "e" # remember, you should not use the same variable twice in the same program # so if you used the variable index, use something else # Write the code to count the number of times the letter y appears in the school variable # print the total word = "McHenry County College" count = 0 for letter in word: if letter == 'y': count += 1 print count # create a variable named college and store the upper case version of the variable school in it word = "college" new_word = word.upper() print new_word # check to see if Count is in the school variable # check to see if count is in the school variable
cef9b68ab180df9f90383c574721d81bb9ca9cef
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/dynamic_programming/fibonacci.py
1,976
4.125
4
""" This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. """ class Fibonacci: def __init__(self, N=None): self.fib_array = [] if N: N = int(N) self.fib_array.append(0) self.fib_array.append(1) for i in range(2, N + 1): self.fib_array.append(self.fib_array[i - 1] + self.fib_array[i - 2]) elif N == 0: self.fib_array.append(0) print(self.fib_array) def get(self, sequence_no=None): """ >>> Fibonacci(5).get(3) [0, 1, 1, 2, 3, 5] [0, 1, 1, 2] >>> Fibonacci(5).get(6) [0, 1, 1, 2, 3, 5] Out of bound. >>> Fibonacci(5).get(-1) [0, 1, 1, 2, 3, 5] [] """ if sequence_no is not None: if sequence_no < len(self.fib_array): return print(self.fib_array[: sequence_no + 1]) else: print("Out of bound.") else: print("Please specify a value") if __name__ == "__main__": print("\n********* Fibonacci Series Using Dynamic Programming ************\n") print("\n Enter the upper limit for the fibonacci sequence: ", end="") try: N = int(input().strip()) fib = Fibonacci(N) print( "\n********* Enter different values to get the corresponding fibonacci " "sequence, enter any negative number to exit. ************\n" ) while True: try: i = int(input("Enter value: ").strip()) if i < 0: print("\n********* Good Bye!! ************\n") break fib.get(i) except NameError: print("\nInvalid input, please try again.") except NameError: print("\n********* Invalid input, good bye!! ************\n") import doctest doctest.testmod()
49816f40fe5e9cc6ac34f14a2b6c3f245f48837a
Faizah-Binte-Naquib/Program-List
/Array/6.py
412
4.15625
4
# ### 6. Find k-th maximum and k-th minimum from an array. # * Summary: Finds the kth minimum and maximum value in an array # * Input: k # * Output: kth minimum and kth maximum term # In[81]: arr=[7,10,4,3,20,15] #input array print(arr) k=int(input("Enter value of k:")) asc_arr=sorted(arr) desc_arr=sorted(arr,reverse=True) print("Kth min term",asc_arr[k-1]) print("Kth max term",desc_arr[k-1])
f0def7f2d2cf2dfdf04d3f2b1ae2aac107f2b6e0
mingyyy/dataquest_projects
/euler/Problem_2-Even_Fibonacci_numbers.py
569
3.96875
4
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ x1, x2, n, s = 1, 2, 0, 2 fibonacci = [x2] total = 4000000 while n < total: n = x1 + x2 x1, x2 = x2, n # fibonacci.append(n) if n % 2 == 0 and n < total: fibonacci.append(n) s += n print(fibonacci) print(s) # 4613732
545e67d7c1945be9b88aa8ff67e6802ac1a7f319
hy299792458/LeetCode
/python/211-addAndSearch.py
1,718
3.609375
4
class WordDictionary(object): #using prefix tree def __init__(self): self.diction = [{}] def addWord(self, word): pos = 0 for char in word: if char not in self.diction[pos]: self.diction[pos][char] = len(self.diction) self.diction.append({}) pos = self.diction[pos][char] char = '$' if char not in self.diction[pos]: self.diction[pos][char] = len(self.diction) self.diction.append({}) pos = self.diction[pos][char] def search(self, word): def match(word, i, pos): if i == len(word): if '$' in self.diction[pos]: return True return False if word[i] == '.': return any(match(word, i + 1, self.diction[pos][k]) for k in self.diction[pos]) elif word[i] in self.diction[pos]: return match(word, i + 1, self.diction[pos][word[i]]) return False return match(word, 0, 0) class WordDictionary(object): #use length list def __init__(self): self.word_dict = collections.defaultdict(list) def addWord(self, word): if word: self.word_dict[len(word)].append(word) def search(self, word): if not word: return False if '.' not in word: return word in self.word_dict[len(word)] for v in self.word_dict[len(word)]: # match xx.xx.x with yyyyyyy for i, ch in enumerate(word): if ch != v[i] and ch != '.': break else: return True return False
88256cb4fa7257eea85ba7b017827fb79f3be94c
sreedharg/leetcode
/21_linked_list.py
1,296
4.0625
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): a = self value = '' while a: value = value + str(a.val) + '->' a = a.next return value class Solution(object): def _set_value(self, x): if self.head is None: self.head = self.tail = ListNode(x.val) else: self.tail.next = ListNode(x.val) self.tail = self.tail.next def mergeTwoLists(self, a, b): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ self.head = None self.tail = None while a is not None: if b is None or a.val < b.val: self._set_value(a) a = a.next else: self._set_value(b) b = b.next while b is not None: self._set_value(b) b = b.next return self.head if __name__ == '__main__': l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(4) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(4) sol = Solution() print(sol.mergeTwoLists(l1, l2))
ba6663c677f39ecdffb1dc9d13aa2fc26add2b4c
rruanes/codewars
/stray_number.py
491
4.125
4
# You are given an odd-length array of integers, in which all of them are the same, except for one single number. # Complete the method which accepts such an array, and returns that single different number. # The input array will always be valid! (odd-length >= 3) # Examples # [1, 1, 2] ==> 2 # [17, 17, 3, 17, 17, 17, 17] ==> 3 def stray(arr): stray = [k for k in arr if arr.count(k) == 1] return stray.pop() arr = [1, 1, 2] arr2 = [17, 17, 3, 17, 17, 17, 17] print(stray(arr2))
61709d92279d62402aea8d301ccc707e16ecb6e8
facumen/1-Parcial
/1k3_PrimerParcial.py
1,912
3.609375
4
def es_vocal(a): vocales = 'aeiou' return a in vocales def es_consonante(a): consonantes = 'qwrtypsdfghjklñzxcvbnm' return a in consonantes cl = ctl = cp = may1 = may2 = cant_v = cant_c = item3 = item4 = 0 flagItem1 = flagL = False texto = input("Ingrese un texto finalizado en '.': ") for i in range(len(texto)): if texto[i] != ' ' and texto[i] != '.': cl += 1 ctl += 1 ult_letra = texto[i] if es_vocal(texto[i]): cant_v += 1 else: if es_consonante(texto[i]): cant_c += 1 if texto[i] == 'c' and texto[i + 1] == 'h': item3 += 1 if cl == 1 and texto[i] == 'l': flagL = True else: cp +=1 if not flagItem1: may1 = cl may2 = cp flagItem1 = True else: if cl > may1: may1 = cl may2 = cp if flagL and es_vocal(ult_letra): item4 += 1 cl = 0 flagL = False porc1 = cant_v * 100 // ctl porc2 = cant_c * 100 // ctl cant_totalCH = ctl - item3 print('\nCantidad total de caracteres:', ctl) print('Cantidad total de palabras:', cp) print('La cantidad de caracteres de la palabra mas larga es:', may1, 'y su posicion es:' ,may2) print('La cantidad total de consonantes en el texto es de:', cant_c, 'y de vocales:' ,cant_v) print('El porcentaje de consonantes sobre el total de los caracteres es de:', porc2, '%') print('El porcentaje de vocales sobre el total de los caracteres es de:', porc1, '%') print('Cantidad de veces que aparece "ch" en el texto:', item3) print('En el caso de que "ch" se contara como una letra, el total de letras seria:', cant_totalCH) print('La cant. de palabras que comienzan con "l" y terminan en vocal son:', item4, '\n') input("ENTER para salir")
18c85e7944c460cdd514d61040c62b781ba7a63b
sarahvestal/ifsc-1202
/Unit 3/03.09 Next Day.py
845
4.40625
4
#Prompt for a month (an integer from 1 to 12) and a day in the month (an integer from 1 to 31) in a common year (not a leap year). #Print the month and the day of the next day after it. #The first test corresponds to March 30 - next day is March 31 #The second test corresponds to March 31 - next day is April 1 #The third test corresponds to December 31 - next day is January 1 #Enter Month: 3 #Enter Day: 30 #Next Day: 3/31 month = int(input("Enter an integer representing the month of the year: ")) #day = int(input("Enter an integer representing the day of the month: ")) if month == 2: monthdays = 28 elif month == 4 or 6 or 9 or 11: monthdays = 30 else: monthdays = 31 #if day < monthdays: # day += 1 print int(monthdays) #if day == monthdays: # day == 1 and month += 1 #print ("Next Day: {}{}".format(month, day))
c764dfc84b69fcb756a4475e261d1822162c4479
uzdevs/week5
/pytest_examples.py/test_example.py
684
3.671875
4
def greet(name): print("Welcome " + name.title()+"!") def talk(name): print(f"Hey, {name}! How are you?") def invite_to_dinner(): print(f'We are having a dinner tonight. Please come over.') def goodbye(name, score): print(f"Thank for coming, see you next time, {name}.") if score > 5: return True else: return False def test_review_dinner(): greet("john") talk("john") invite_to_dinner() satisfied = goodbye("John",6) == True assert satisfied == True def test_review_dinner_navigate(): greet("john") talk("john") invite_to_dinner() satisfied = goodbye("John",4) assert satisfied == False
1e621d2bb915f8a51acab2f3b11c48dc4e1b88aa
nnsdtr/OOP-Python
/A_mecanica_das_Classes_e_Instancias/14-Working-with-Class-and-Instance-data.py
1,527
4.28125
4
# Nesta lição, veremos como os dados da classe se relacionam com # os dados da instância e começaremos a falar sobre situações nas # quais podemos querer armazenar dados na classe. class InstanceCounter(object): count = 0 def __init__(self, value): self.attribute = value InstanceCounter.count += 1 def set_value(self, new_value): self.attribute = new_value def get_value(self): return self.attribute def get_count(self): return InstanceCounter.count a = InstanceCounter(8) b = InstanceCounter(15) c = InstanceCounter(23) print() for obj in (a, b, c): print('Attribute value of obj: {}'.format(obj.get_value())) print('count: {}'.format(obj.get_count())) print(InstanceCounter.count) print(a.count) # O valor é olhado primeiro na instância, depois na classe. # Portanto, nesta lição, vimos um exemplo de atributos de classe, o que também chamamos # de dados de classe, e como o Python nos permite definir valores na classe que são # acessíveis através de cada uma das instâncias e também da própria classe. # # O que estamos construindo aqui nestas lições até agora é uma compreensão da estrutura # que os desenvolvedores de software usam no mundo inteiro para criar código que usamos # todos os dias. À medida em que aprendermos mais, começaremos a ver maneiras pelas quais # podemos aplicar essa estrutura ao nosso próprio código. # # Mas há mais para aprender sobre o paradigma orientado a objetos.
75813638312bdc660ff036cddd23bc9b2d6115fe
MirekPz/PyCode
/01_typy_zmienne_2019-10-09/zad-4.py
1,120
4.15625
4
""" Utwórz skrypt, który zapyta użytkownika o tytuł książki, nazwisko autora, liczbę stron, a następnie: - Sprawdź czy tytuł i nazwisko składają się tylko z liter, natomiast liczba stron jest wartością liczbową. - Użytkownicy bywają leniwi. Nie zawsze zapisują tytuły i nazwisko z dużej litery – popraw ich - Połącz dane w jeden ciąg book za pomocą spacji - Policz liczbę wszystkich znaków w napisie book """ title = input("Podaj tytuł książki: ") author = input("Nazwisko autora: ") pages = input("Liczba stron: ") print("_" * 40) title_without_spaces = title.replace(' ', '') # title without spaces print("Czy tylko litery w tytule:", title_without_spaces.isalpha()) author_without_spaces = author.replace(" ", "") # name of author without spaces print("Czy tylko litery w nazwisku:", author_without_spaces.isalpha()) print("Czy liczba stron jest liczbą naturalną:", pages.isdigit()) print("Tytuł:", title.capitalize()) print("Autor:", author.title()) book = title + " " + author + " " + str(pages) print("book = ", book) print("Liczba znaków w napisie book:", len(book))
1f558be200b5eab547cbdc6d6db316af0c7b63ba
gabriellaec/desoft-analise-exercicios
/backup/user_139/ch42_2020_04_11_14_07_03_697917.py
417
3.5625
4
lista_palavras = [] i = 0 while True: lista_palavras.append(input('Escreva uma palavra: ')) palavra = list(lista_palavras[i]) if palavra [0] == 'f' and palavra [1] == 'i' and palavra [2] == 'm': del lista_palavras[-1] break elif palavra [0] == 'a': i += 1 else: del lista_palavras[i] i2 = 0 while i2 < len(lista_palavras): print (lista_palavras[i2]) i2 += 1
a05a4c02253ee3a82aa62eeafb55b7638f01dc17
corrodedHash/bruteFolder
/brutefolder/direction.py
1,330
4.125
4
"""Keeps function to modify directions""" from typing import List import enum @enum.unique class Direction(enum.Enum): """ Enum for 2D direction """ up = 1 right = 2 down = 3 left = 4 def __str__(self) -> str: return self.name def __repr__(self) -> str: return self.name DIR_INT_MAP = {Direction.up: 0, Direction.right: 1, Direction.down: 2, Direction.left: 3} INT_DIR_MAP = {DIR_INT_MAP[k]: k for k in DIR_INT_MAP} DIR_CHAR_MAP = {Direction.up: 'u', Direction.left: 'l', Direction.down: 'd', Direction.right: 'r'} CHAR_DIR_MAP = {DIR_CHAR_MAP[k]: k for k in DIR_CHAR_MAP} def turn(start: Direction, turn_dir: Direction) -> Direction: """Turns given direction in given direction""" start_int = DIR_INT_MAP[start] turn_dir_int = DIR_INT_MAP[turn_dir] return INT_DIR_MAP[(start_int + turn_dir_int) % 4] def get_turn_diff(start: Direction, end: Direction) -> Direction: """Returns the direction that is needed to turn from start to end""" start_int = DIR_INT_MAP[start] end_int = DIR_INT_MAP[end] return INT_DIR_MAP[(end_int - start_int) % 4] def str_to_dir_list(inp: str)-> List[Direction]: """Return list with directions as given in input""" return [CHAR_DIR_MAP[x] for x in inp.lower()]
8c14cdc8f26d6840618ed421d6b6e5795841403b
Uthaeus/pynative
/strings/hyphen.py
124
4.0625
4
def hyphen(s): arr = s.split('-') for x in arr: print(x) str1 = 'Emma-is-a-data-scientist' hyphen(str1)
d536584d3d9e36f6feb5d0cc655abba59acd37a7
armsky/Preps
/Facebook/phone/Binary Tree - Diameter.py
997
4.40625
4
""" Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them. """ class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 return max(self.length(root.left) + self.length(root.right), self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right)) def length(self, root): if not root: return 0 return max(self.length(root.left), self.length(root.right)) + 1
c638dd0df2e5aa6c6adf0ec4b747b4f1a5385fee
pointwestMac/MLTraining2018
/Session 1/Exercise 1/Liang_SharlaineLouisse/test-script.py
807
3.578125
4
import numpy as np import time # load dataset dataset = np.loadtxt("test-data.csv", delimiter=",",skiprows=1) X = dataset[:,0] Y = dataset[:,1] #test print print("No Errors!") print(len(X)) print(len(Y)) start_time = time.time() Z = [] for i in range(0, len(X)-1): Z.append(X[i]*Y[i]) print(sum(Z)) for_time = time.time() - start_time print("For loop ran for %s seconds ---" % (for_time)) start_time = time.time() print(np.matmul(X, Y)) mat_time = time.time() - start_time print("Matrix multiplication ran for %s seconds ---" % (mat_time)) if mat_time > for_time: print("For loop is faster by") elif for_time > mat_time: print("Matrix multiplication is faster by") else: print("Both fast") print("% s seconds" % (max(for_time, mat_time) - min(for_time, mat_time)))
d8c913bf0551bb7fe53bfc350aca20aaef28cd18
chriskbwong/Largest-Prime-Factor
/Largest_Prime_Number.py
676
3.53125
4
''' prompt: The prime factors of 13195 are 5, 7, 13 and 29. Thus, the largest prime factor of 13195 is 29. What is the largest prime factor of the number 600851475143 ? ''' def prime(n): div_count = 0 factor = 1 if n <= 1: return False while div_count < 2: if n % factor == 0: div_count += 1 factor += 1 else: factor += 1 if n == (factor - 1): return True else: return False def LPF(num): if prime(num): return num factor = num - 1 while factor > 1: if num % factor == 0: if prime(factor) == True: return factor else: factor -= 1 else: factor -= 1 print(LPF(13195))
0247b263c55ff3fa8074519c1364e9c9e69767ba
KIMBEOBWOO/python-study
/practice-02/q2.py
173
3.671875
4
# 자연수 13이 홀수인지 짝수인지 판별할 수 있는 방법에 대해 말해 보자. N = 13 if(N % 2 == 0): print('짝수') else: print('홀수')
b462e9b6d0b644b0da3901a19a8adca8dd0decdf
jokmos/fuzzies
/fizzbuzz.py
722
3.8125
4
#!/usr/local/bin/python3 # Fizz buzz test program """Usage ./fizzbuzz.py <filename>""" import sys def fizzbuzz(num, a, b): msg = "" if num % a == 0: msg += "F" if num % b == 0: msg += "B" return msg or str(num) def process_input(name): infile = open(name, 'r') for line in infile: variables = line.split() N = int(variables[2]) for i in range(1, N): print(fizzbuzz(i, int(variables[0]), int(variables[1])), end=' ') print(fizzbuzz(N, int(variables[0]), int(variables[1]))) def main(): if len(sys.argv) <= 1: sys.exit(__doc__) file_name = sys.argv[1] process_input(file_name) if __name__ == "__main__": main()
5ba3b93d92752fef9b130aff76b9b32e95c2f4da
isolde18/Class
/name.py
274
4.21875
4
def main(): First_Name,Last_Name=info() print ("Your name in reverse is ", Last_Name, First_Name) def info(): fName=input ("Please enter your First Name: ") lName=input ("Please enter your Last name: ") return fName, lName main()
680ee744db18a3744b5553d300edd2caec025d48
xutkarshjain/HackerRank-Solution
/Python/String/Merge the Tools!.py
319
3.5
4
def merge_the_tools(string, k): L=len(string) for i in range(0,L,k): t='' for j in range(min(L-i,k)): if string[i+j] not in t: t+=string[i+j] print(t) if __name__ == '__main__': string, k = input(), int(input()) merge_the_tools(string, k)
cd688e0a5b260ef7f9162ead6cbff83e25a009e2
Aislingpurdy01/CA177
/football-result-gaelic.py
182
3.90625
4
#!/usr/bin/env python a = input() * 3 b = input() c = input() * 3 d = input() if a + b > c + d: print "Home win." elif a + b < c + d: print "Away win." else: print "Draw."
4fcf5c4d7bbb78f71dea8d01e70b224048a13f72
microease/bit-Python-language-programming
/Test6/test1.py
1,493
3.703125
4
# 第一题 数字不同数之和 # 描述‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬ # 获得用户输入的一个整数N,输出N中所出现不同数字的和。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬ # # 例如:用户输入 123123123,其中所出现的不同数字为:1、2、3,这几个数字和为6。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫ # # 输入输出示例 # 输入 输出 # 123123123 6 # 解答代码 # 思路:用N接收输入的数字字符串,接着利用set()转为集合去重,最后迭代集合求和。这里要注意要把字符串类型转化为数字类型,不然会报错。 # 数字不同数之和 N = input() st = set(N) sum = 0 for i in st: sum += int(i) print(sum) d= {'a': 1, 'b': 2, 'b': '3'} print(d['b'])
64876d62dc58a18506bbc8a6e8fa8c9c2c642942
Reetishchand/Leetcode-Problems
/01570_DotProductofTwoSparseVectors_Medium.py
1,454
4.15625
4
'''Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. Follow up: What if only one of the vectors is sparse? Example 1: Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] Output: 8 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8 Example 2: Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2] Output: 0 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 Example 3: Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4] Output: 6 Constraints: n == nums1.length == nums2.length 1 <= n <= 10^5 0 <= nums1[i], nums2[i] <= 100''' class SparseVector: def __init__(self, nums: List[int]): self.arr=nums # Return the dotProduct of two sparse vectors def dotProduct(self, vec: 'SparseVector') -> int: ans=0 for i in range(len(vec.arr)): ans+=vec.arr[i]*self.arr[i] return ans # Your SparseVector object will be instantiated and called as such: # v1 = SparseVector(nums1) # v2 = SparseVector(nums2) # ans = v1.dotProduct(v2)
6182677efc8f21bcfd1836d651dd72a20f4833f3
lukejskim/sba19-seoulit
/Sect-A/source/sect06_function/s650_scope_global.py
611
3.90625
4
# 지역변수와 전역변수 param = 10 strdata = '전역변수' def func1(): strdata = '지역변수' print('func1.strdata = %s, id = %d' % (strdata, id(strdata))) def func2(param): param = 20 print('func2.param = %d, id = %d' % (param, id(param))) def func3(): global param param = 30 print('func3.param = %d, id = %d' % (param, id(param))) func1() print('main1.strdata = %s, id = %d' % (strdata, id(strdata))) print('-'*50) func2(param) print('main2.param = %d, id = %d' % (param, id(param))) print('-'*50) func3() print('main3.param = %d, id = %d' % (param, id(param)))
326110e06fcce09317d6699f8bd4a016cbd653ae
jamesrmuir/python-workbook
/Python Workbook/16. IMPERIAL AND METRIC CONVERTOR [2-5].py
2,431
4.0625
4
#Imperial and metric convertor [2-5] from commonFunctions import * #Custom file make sure it is available repeating = True while repeating: print(""" 1. KM to Miles 2. Miles to KM 3. KM to Meters 4. Meters to KM 5. Meters to CM 6. CM to Meters 7. Feet to Inches 8. Inches to Feet 9. CM to Inches 10. Inches to CM """) choice = int_input("Please enter a number: ") if choice == 1: userInput = float_input("Enter number of KM: ") output = userInput * 0.621371 print("{} KM is {} miles.".format(userInput, output)) elif choice == 2: userInput = float_input("Enter number of Miles: ") output = userInput * 1.60934 print("{} Miles is {} KM.".format(userInput, output)) elif choice == 3: userInput = float_input("Enter number of KM: ") output = userInput * 1000 print("{} KM is {} Meters.".format(userInput, output)) elif choice == 4: userInput = float_input("Enter number of Meters: ") output = userInput / 1000 print("{} Meters is {} KM.".format(userInput, output)) elif choice == 5: userInput = float_input("Enter number of Meters: ") output = userInput * 100 print("{} Meters is {} CM.".format(userInput, output)) elif choice == 6: userInput = float_input("Enter number of CM: ") output = userInput / 100 print("{} CM is {} Meters.".format(userInput, output)) elif choice == 7: userInput = float_input("Enter number of Feet: ") output = userInput * 12 print("{} Feet is {} Inches.".format(userInput, output)) elif choice == 8: userInput = float_input("Enter number of Inches: ") output = userInput / 12 print("{} Inches is {} Feet.".format(userInput, output)) elif choice == 9: userInput = float_input("Enter number of CM: ") output = userInput / 2.54 print("{} CM is {} Inches.".format(userInput, output)) elif choice == 10: userInput = float_input("Enter number of Inches: ") output = userInput * 2.54 print("{} Inches is {} CM.".format(userInput, output)) while True: userRepeat = input("Do you want to repeat? \nEnter Y/N: ").lower() if userRepeat == "y": break elif userRepeat == "n": repeating = False break else: print("Enter valid input.")
8aa48b54c18e6447d98094a36b9ea34252b4b112
tahmid-tanzim/problem-solving
/codility/min-number-of-car.py
3,238
4
4
#!/usr/bin/python3 from typing import List """ Task 2 - 15% A group of friends is going on a holiday together. They have come to a meeting point (the start of the journey) using N cars. There are P[K] people and S[K] seats in the K-th car for K in range [0..N-1]. Some seats in the cars may be free, so it is possible for some friends to change the car they are in. the friends have decided that, in order to be ecological, they will leave some cars parked at the meeting point and travel with as few cars as possible. Write a function that given two arrays P and S, consists of N integers each, return the minimum number of cars needed to take all friend on holiday. Examples 1. Given P = [1, 4, 1] and S = [1, 5, 1], The function should return 2 2. Given P = [4, 4, 2, 4] and S = [5, 5, 2, 5], The function should return 3 3. Given P = [2, 3, 4, 2] and S = [2, 5, 7, 2], The function should return 2 Write an efficient algorithms for following assumptions: - N is an integer within the range [1..100,000] - each element of array P and S is an integer within the range [1..9] - P[K] <= S[K] for each K within the range [0..N-1] """ def findMinNumberOfCar(P: List[int], S: List[int]) -> int: total_cars = len(P) filled_seat = list() empty_seat = list() for p, s in zip(P, S): if p == s: filled_seat.append(s) else: empty_seat.append(s - p) while len(filled_seat) > 0 and len(empty_seat) > 0: min_idx = filled_seat.index(min(filled_seat)) max_idx = empty_seat.index(max(empty_seat)) if filled_seat[min_idx] <= empty_seat[max_idx]: empty_seat[max_idx] -= filled_seat[min_idx] del filled_seat[min_idx] total_cars -= 1 else: filled_seat[min_idx] -= empty_seat[max_idx] del empty_seat[max_idx] return total_cars if __name__ == '__main__': inputs = ( { "P": [1, 4, 1], "S": [1, 5, 1], "expected": 2 }, { "P": [4, 4, 2, 4], "S": [5, 5, 2, 5], "expected": 3 }, { "P": [2, 3, 4, 2], "S": [2, 5, 7, 2], "expected": 2 }, { "P": [1, 2, 3, 4, 5], "S": [1, 2, 3, 4, 5], "expected": 5 }, { "P": [1, 2, 3, 4, 5], "S": [1, 2, 4, 4, 5], "expected": 4 }, { "P": [1, 3, 4, 5], "S": [2, 3, 4, 5], "expected": 4 }, { "P": [1, 2, 1, 5, 3], "S": [1, 2, 1, 7, 3], "expected": 3 }, { "P": [1, 2, 3], "S": [1, 2, 3], "expected": 3 }, ) test_passed = 0 for i, val in enumerate(inputs): output = findMinNumberOfCar(val["P"], val["S"]) if output == val['expected']: print(f"{i}. CORRECT Answer\nOutput:{output}\nExpected:{val['expected']}\n\n") test_passed += 1 else: print(f"{i}. WRONG Answer\nOutput:{output}\nExpected:{val['expected']}\n\n") print(f"Passed - {test_passed}/{i + 1}")
70fa256d9a0ff8f0576f757c5bdf5eca0d5657c4
ancnudde/Artificial_intelligence
/utils.py
4,622
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import requests import os from time import sleep def download(url, fileName): """ Downloads file given by url to given filename. If already something exists with this filename, it replaces this. It is implemented with streams so that also very large files can be downloaded without having a memory overload. """ """The function will do at most 10 attemps to download the file""" for i in range(10): try: try: """Delete existing file with filename""" os.remove(fileName) except: pass """file is downloaded in chunks""" with requests.get(url, stream=True) as r: r.raise_for_status() with open(fileName, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): if chunk: f.write(chunk) return fileName except: """Wait between requests increases because some servers will block it when to many requests are asked at once""" print("Download", url,"failed:",i) sleep(5*(i+1)) def uniprotRetrieve(fileName, query="",format="list",columns="",include="no",compress="no",limit=0,offset=0): """Downloads file from uniprot for given parameters If no parameters are given the function will download a list of all the proteins ID's. More information about how the URL should be constructed can be found on: https://www.uniprot.org/help/api%5Fqueries Parameters ---------- fileName : str name for the downloaded file query : str (Default='') query that would be searched if as you used the webinterface on https://www.uniprot.org/. If no query is provided, all protein entries are selected. format : str (Default='list') File format you want to retrieve from uniprot. Available format are: html | tab | xls | fasta | gff | txt | xml | rdf | list | rss columns : str (Default='') Column information you want to know for each entry in the query when format tab or xls is selected. include : str (Default='no') Include isoform sequences when the format parameter is set to fasta. Include description of referenced data when the format parameter is set to rdf. This parameter is ignored for all other values of the format parameter. compress : str (Default='no') download file in gzipped compression format. limit : int (Default=0) Limit the amount of results that is given. 0 means you download all. offset : int (Default=0) When you limit the amount of results, offset determines where to start. Returns ------- fileName : str Name of the downloaeded file. """ def generateURL(baseURL, query="",format="list",columns="",include="no",compress="no",limit="0",offset="0"): """Generate URL with given parameters""" def glueParameters(**kwargs): gluedParameters = "" for parameter, value in kwargs.items(): gluedParameters+=parameter + "=" + str(value) + "&" return gluedParameters.replace(" ","+")[:-1] #Last "&" is removed, spacec replaced by "+" return baseURL + glueParameters(query=query, format=format, columns=columns, include=include, compress=compress, limit=limit, offset=offset) URL = generateURL("https://www.uniprot.org/uniprot/?", query=query, format=format, columns=columns, include=include, compress=compress, limit=limit, offset=offset) return download(URL, fileName) def mapping(queryFile,outputFile, parameterDictionary): def addQuery(): with open(queryFile) as f: parameterDictionary["query"]="".join(f.readlines()) def main(): addQuery() url = 'https://www.uniprot.org/uploadlists/' data = urllib.parse.urlencode(parameterDictionary) data = data.encode('utf-8') req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as f: response = f.read() with open(outputFile, 'b+w') as f: f.write(response) for i in range(10): main() try: if os.stat(outputFile).st_size != 0: break except: print("Try",i,"Failed") sleep(5*(i+1))
1fb7b6479f9359cb11e8f67e560a0dbe21e3f418
mccarvik/cookbook_python
/14_testing_debugging_exceptions.py/9_raise_except_resp_another_except.py
1,069
3.875
4
# raise from exception specifies raising another exception "from" a previous one # chains them together def example(): try: int('N/A') except ValueError as e: raise RuntimeError('A parsing error occurred') from e example() try: example() except RuntimeError as e: print("It didn't work:", e) # can look at the __cause__ attribute for more info if e.__cause__: print('Cause:', e.__cause__) def example2(): try: int('N/A') except ValueError as e: # implicit chained exceptions when exception occurs in an "except" block print("Couldn't parse:", err) example2() # If you want to suppress chaining, use "from None" def example3(): try: int('N/A') except ValueError: raise RuntimeError('A parsing error occurred') from None example3() # Should probably prefer this style try: pass except SomeException as e: raise DifferentException() from e # Here, not as clear which is getting raised try: pass except SomeException: raise DifferentException()