blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
cafa19ec507d2c4336453156e48745d0741bfa53
PacktPublishing/The-Complete-Python-Course
/2_intro_to_python/lectures/11_comprehensions_with_conditionals/code.py
691
3.734375
4
ages = [22, 35, 27, 21, 20] odds = [n for n in ages if n % 2 == 1] # -- with strings -- friends = ["Rolf", "ruth", "charlie", "Jen"] guests = ["jose", "Bob", "Rolf", "Charlie", "michael"] friends_lower = [f.lower() for f in friends] present_friends = [ name.capitalize() for name in guests if name.lower() in friends_lower ] # -- nested list comprehensions -- # Don't do this, because it's almost completely unreadable. # Splitting things out into variables is better. friends = ["Rolf", "ruth", "charlie", "Jen"] guests = ["jose", "Bob", "Rolf", "Charlie", "michael"] present_friends = [ name.capitalize() for name in guests if name.lower() in [f.lower() for f in friends] ]
f8fad97a0ca47a3f5e609db18f89a04eed5eaa96
RubenH101/Calculator
/CalculatorProject.py
6,626
3.65625
4
from tkinter import* import math cal= Tk() cal.geometry('442x610') cal.configure(bg='mediumblue') cal.title("Calculator") callabel = Label(cal,text="Calculator",font=('arial',100,'bold')) def clickbut(numbers): current = caltext.get() caltext.delete(0, END) caltext.insert(0, str(current) + str(numbers)) def button_add(): first_number = caltext.get() global f_num global math math = "addition" f_num = int(first_number) caltext.delete(0, END) def button_subtract(): first_number = caltext.get() global f_num global math math = "subtraction" f_num = int(first_number) caltext.delete(0, END) def button_multiply(): first_number = caltext.get() global f_num global math math = "multiplication" f_num = int(first_number) caltext.delete(0, END) def button_division(): first_number = caltext.get() global f_num global math math = "division" f_num = int(first_number) caltext.delete(0, END) def button_clear(): caltext.delete(0, END) def button_sqrt(): first_number = caltext.get() global f_num global math math = "square root" f_num = int(first_number) caltext.delete(0, END) def button_percen(): first_number = caltext.get() global f_num global math math = "percentage" f_num = int(first_number) caltext.delete(0, END) def button_exp(): first_number = caltext.get() global f_num global math math = "exponent" f_num = int(first_number) caltext.delete(0, END) def button_change(): first_number = caltext.get() global f_num global math math = "change" f_num = int(first_number) caltext.delete(0, END) def button_pie(): first_number = caltext.get() global f_num global math math = "pie" f_num = int(first_number) caltext.delete(0, END) def button_2nd(): first_number = caltext.get() global f_num global math math = "2nd" f_num = int(first_number) caltext.delete(0, END) def button_equal(): second_number = caltext.get() caltext.delete(0, END) if math == 'addition': caltext.insert(0, f_num + int(second_number)) if math == 'subtraction': caltext.insert(0, f_num - int(second_number)) if math == 'multiplication': caltext.insert(0, f_num * int(second_number)) if math == 'division': try: caltext.insert(0, f_num / int(second_number)) except ZeroDivisionError: caltext.insert(0, str('ERROR')) if math == 'square root': caltext.insert(0, f_num ** 0.5) if math == 'exponent': caltext.insert(0, f_num ** int(second_number)) if math == 'percentage': caltext.insert(0, (f_num * int(second_number))/100) if math == 'change': caltext.insert(0, f_num / -1) if math == 'pie': caltext.insert(m.pi) if math == '2nd': caltext.insert(0, f_num ** 2) caltext = Entry(cal,width=55,borderwidth=13,font=('oswald',10,'bold')) caltext.grid(row=0, column=0, columnspan=4, padx=10, pady=10) but1=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue', fg='black',command=lambda:clickbut(1),text='1',font=('oswald',15,'bold')).grid(row=1, column=2) but2=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue', fg='black',command=lambda:clickbut(2),text='2',font=('oswald',15,'bold')).grid(row=2, column=0) but3=Button(cal,padx=38,pady=10,bd=5,bg='aqua', fg='black',command=lambda:clickbut(3),text='3',font=('oswald',15,'bold')).grid(row=2, column=1) but4=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue', fg='black',command=lambda:clickbut(4),text='4',font=('oswald',15,'bold')).grid(row=2, column=2) but5=Button(cal,padx=35,pady=10,bd=5,bg='aqua', fg='black',command=lambda:clickbut(5),text='5',font=('oswald',15,'bold')).grid(row=3, column=0) but6=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue', fg='black',command=lambda:clickbut(6),text='6',font=('oswald',15,'bold')).grid(row=3, column=1) but7=Button(cal,padx=35,pady=10,bd=5,bg='aqua', fg='black',command=lambda:clickbut(7),text='7',font=('oswald',15,'bold')).grid(row=3, column=2) but8=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue', fg='black',command=lambda:clickbut(8),text='8',font=('oswald',15,'bold')).grid(row=4, column=0) but9=Button(cal,padx=35,pady=10,bd=5,bg='aqua', fg='black',command=lambda:clickbut(9),text='9',font=('oswald',15,'bold')).grid(row=4, column=1) but0=Button(cal,padx=35,pady=10,bd=5,bg='aqua',command=lambda:clickbut(0),text='0',font=('oswald',15,'bold')).grid(row=1, column=1) butsub=Button(cal,padx=35,pady=10,bd=5,bg='aqua', fg='black',command=button_subtract,text='-',font=('oswald',15,'bold')).grid(row=6,column=2) butadd=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue', fg='black',command=button_add,text='+',font=('oswald',15,'bold')).grid(row=5, column=0) butmul=Button(cal,padx=35,pady=10,bd=5,bg='aqua', fg='black',command=button_multiply,text='×',font=('oswald',15,'bold ')).grid(row=6,column=0) butclear=Button(cal,padx=200,pady=15,bd=5,bg='powderblue',command=button_clear,text='CE',font=('oswald',15,'bold')).grid(row=8, column=0, columnspan=4) butdiv=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue',command=button_division,text='÷',font=('oswald',15,'bold')).grid(row=6, column=1) butequal=Button(cal,padx=35,pady=250,bd=5,bg='steelblue',fg='white',command=button_equal,text='=',font=('oswald',15,'bold')).grid(row=1, column=3, rowspan=8) butsqrt=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue',command=button_sqrt,text='√',font=('oswald',15,'bold')).grid(row=7, column=0) butexp=Button(cal,padx=35,pady=13,bd=5,bg='aqua',command=button_exp,text='xⁿ',font=('oswald',13,'bold')).grid(row=7, column=1) butpercen=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue',command=button_percen,text='%',font=('oswald',15,'bold')).grid(row=7, column=2) butplussub=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue',command=button_change,text='±',font=('oswald',15,'bold')).grid(row=4, column=2) butpie=Button(cal,padx=32,pady=10,bd=5,bg='light blue',command=button_pie,text='π',font=('oswald',15,'bold')) but2nd=Button(cal,padx=35,pady=12,bd=5,bg='aqua',command=button_2nd,text='x²',font=('oswald',12,'bold')).grid(row=5, column=1) button_quit=Button(cal,text="EXIT",padx=35, pady=15, bd=10, bg='hotpink', fg='white', command=quit).grid(row=1, column=0) butdot=Button(cal,padx=35,pady=10,bd=5,bg='deepskyblue', fg='black',command=lambda:clickbut('.'),text='.',font=('oswald',15,'bold')).grid(row=5, column=2) cal.mainloop()
90aa93be4b574939d568c13f67129c50c4f34d19
ItzMeRonan/PythonBasics
/TextBasedGame.py
423
4.125
4
#--- My Text-Based Adventure Game --- print("Welcome to my text-based adventure game") playerName = input("Please enter your name : ") print("Hello " + playerName) print("Pick any of the following characters: ", "1. Tony ", "2. Thor ", "3. Hulk", sep='\n') characterList = ["Tony", "Thor", "Hulk"] characterNumber = input("Enter the character's number : ") print("You chose: " + characterList[int(characterNumber) -1])
045eb4fa6050cf6db361622253215869793a030d
wsr0727/pythonLessionTest
/strtesr.py
132
3.609375
4
def rvs(s): if s == "": return s else: return rvs(s[1:])+s[0] def main(): print(rvs(s=input())) main()
4c60fb574cb306ecb5565c04c570570a945dd718
Semihozel/Workspace
/Kullanıcı Girişi.py
565
3.84375
4
print("********\n KULLANICI GİRİŞİ\n********") kayıtlıad = "Semih" kayıtlıparola = "12345" kullanıcı_adı = input("Kullanıcı adını giriniz ") parola = input("Parolayı giriniz ") if (kullanıcı_adı == kayıtlıad and kayıtlıparola != parola): print("Parola yanlış") elif (kullanıcı_adı != kayıtlıad and kayıtlıparola == parola): print("Kullanıcı adı yanlış ") elif (kullanıcı_adı != kayıtlıad and kayıtlıparola != parola): print("Kullanıcı adı ve Parola hatalı giriş") else: ("HOŞGELDİNİZ")
46a0b3b6c4d950a602b0085788309b4c7cfe775c
Semihozel/Workspace
/Mükemmel Sayı Bulma.py
364
3.875
4
print("MÜKEMMEL SAYI BULMA") a = int(input("sayı : ")) toplam = 0 for i in range(1, a): if (a % i == 0): print("{} nın bölenleri".format(i)) toplam += i print("bölenlerin toplamı", toplam) if (toplam == a): print("{} mükemmel bir sayıdır".format(a)) else: print("mükemmel sayı değildir")
44743a6d92fd09751136f4ae34699e9947d8a17d
xuyanbo03/study
/python/test/sushu.py
341
3.84375
4
def _odd_iter(): n=1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x:x%n>0 def primes(): yield 2 it = _odd_iter() while True: n=next(it) yield n it = filter(_not_divisible(n),it) for n in primes(): if n<1000: print(n) else: break
6a62ad6dadd132628c486c46bccee578d8fa6d88
jameygronewald/python_challenges
/list_overlap.py
397
3.515625
4
import random # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] a = [] b = [] length_of_a = random.randint(20, 50) length_of_b = random.randint(20, 50) for x in range (length_of_a): a.append(random.randint(1, 100)) for x in range (length_of_b): b.append(random.randint(1, 100)) print(a) print(b) print(list(set([x for x in a if x in b])))
c88bc8dba47119b9fb09fb36ef2782ee8fb04c90
jameygronewald/python_challenges
/guess_word_by_letter.py
731
4.03125
4
word = "EVAPORATE" list = ['_' for char in word] guessed = [] def init(): print() print(*list) while '_' in list: print('\nTry to guess the word!') user_guess = input('Enter a letter to guess: ').upper().strip() if len(user_guess) > 1: print('\nPlease enter only one letter as a guess.') elif user_guess in guessed: print('\nYou already guessed that one. Try a different letter.') else: guessed.append(user_guess) for i in range(len(word)): if word[i] == user_guess: list[i] = user_guess print() print(*list) print(f"\nYou got it! The word was {word}") init()
88764af2f7ea16f7c927cf3c3ffaee41639ea625
jameygronewald/python_challenges
/reverse_word_order.py
193
4.34375
4
def reverse_word_order(): string = input(f"Type a message with multiple words and I will reverse the word order for you. ") print(" ".join(string.split()[::-1])) reverse_word_order()
f5a76219a79e832625c64dd0e16352ecc4f96ac9
SoeZeng/FishC
/P48_1.py
1,379
3.859375
4
# -*- coding: utf-8 -*- """ Created on Tue May 25 13:58:26 2021 @author: DELL """ class LeapYear: def __init__(self): self.year = 2021 def __iter__(self): return self def __next__(self): while not ((self.year % 4 == 0 and self.year % 100 != 0) or (self.year % 400 == 0)): self.year -= 1 year = self.year self.year -= 1 return year leapYears = LeapYear() for i in leapYears: # 循环一次执行一次__next__(),将返回值赋值给i,再对i进行判断,决定是否执行下一次循环 # 若类外没有设置判断条件,需要在类内设置,不满足条件则抛出StopIteration异常,退出for循环 if i >= 2000: print(i) else: break ''' import datetime as dt class LeapYear: def __init__(self): self.now = dt.date.today().year def isLeapYear(self, year): if (year%4 == 0 and year%100 != 0) or (year%400 == 0): return True else: return False def __iter__(self): return self def __next__(self): while not self.isLeapYear(self.now): self.now -= 1 temp = self.now self.now -= 1 return temp '''
a3c5cddfc199013915eb4152ba615e90ced60586
SoeZeng/FishC
/P41_2.py
1,039
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue May 18 16:47:38 2021 @author: DELL """ class Nint(int): def __new__(cls,pref): if isinstance(pref,str): result = 0 for c in pref[:]: result += ord(c) pref = result return int.__new__(cls,pref) ''' elif isinstance(pref,float): print('浮点型数据') result = pref // 1 else: print('整型数据') result = pref return int.__new__(cls,result) ''' print(Nint(123)) print(Nint(1.5)) print(Nint('A')) print(Nint('FishC')) ''' class Nint(int): def __new__(cls, arg=0): if isinstance(arg, str): total = 0 for each in arg: total += ord(each) arg = total return int.__new__(cls, arg) '''
2feb9efd1c4596c1b6fedff272b3b91cefb24927
SoeZeng/FishC
/P42_2.py
1,626
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed May 19 12:14:07 2021 @author: DELL """ class Nstr(str): def __init__(self,s): self.asc = 0 for c in s: self.asc += ord(c) def __add__(self,other): return int(self.asc) + int(other.asc) def __sub__(self,other): return int(self.asc) - int(other.asc) def __mul__(self,other): return int(self.asc) * int(other.asc) def __truediv__(self,other): return int(self.asc) / int(other.asc) def __floordiv__(self,other): return int(self.asc) // int(other.asc) a = Nstr('FishC') b = Nstr('love') print(a+b) print(a-b) print(a/b) print(a//b) print(a*b) ''' class Nstr: def __init__(self, arg=''): if isinstance(arg, str): self.total = 0 for each in arg: self.total += ord(each) else: print("参数错误!") def __add__(self, other): return self.total + other.total def __sub__(self, other): return self.total - other.total def __mul__(self, other): return self.total * other.total def __truediv__(self, other): return self.total / other.total def __floordiv__(self, other): return self.total // other.total ''' ''' class Nstr(int): def __new__(cls, arg=0): if isinstance(arg, str): total = 0 for each in arg: total += ord(each) arg = total return int.__new__(cls, arg) '''
3c221d5ddb50cd037b771d2b33c1f809c550249d
SoeZeng/FishC
/P39_1.py
1,325
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue May 18 11:12:14 2021 @author: DELL """ class Stack: def __init__(self): self.stack = [] def isEmpty(self): print(True) if len(self.stack) == 0 else print(False) def push(self,data): self.stack.append(data) def pop(self): self.stack.remove(self.stack[-1]) def top(self): print(self.stack[-1]) def buttom(self): print(self.stack[0]) s = Stack() s.isEmpty() s.push(666) s.push(888) s.isEmpty() s.top() s.buttom() s.pop() s.isEmpty() ''' class Stack: def __init__(self, start=[]): self.stack = [] for x in start: self.push(x) def isEmpty(self): return not self.stack def push(self, obj): self.stack.append(obj) def pop(self): if not self.stack: print('警告:栈为空!') else: return self.stack.pop() def top(self): if not self.stack: print('警告:栈为空!') else: return self.stack[-1] def bottom(self): if not self.stack: print('警告:栈为空!') else: return self.stack[0] '''
91640393b2028db76feab7459f1bb2706d945403
Spencer-Ross/spencer_ross_proj2
/wsu-pub-crypt.py
6,638
3.765625
4
# imports and globals import sys, argparse, random from random import getrandbits from fastExp import fast_exp from Miller_Rabin import is_prime rands: int = 10 # number of checks for isPrime wordSize: int = 4 # number of bytes/word # Key Related Functions -------------------------------------------------------------- def gen_key(): ''' Generates the public and private keys. It will overwrite existing files of the same name, and the generator is always 2 and the prime is derived from this ''' pubName: str = 'pubkey.txt' priName: str = 'prikey.txt' # these values are hardcoded for the assignment bits: int = 32 gen2: int = 2 prime: int = generator(k=bits) randNum: int = random.randint(a=1, b=(prime-1)) e2: int = fast_exp(base=gen2, exponent=randNum, mod=prime) print('p:', prime, '\tg:', gen2, '\te2:', e2, '\td:', randNum) with open(pubName, 'w') as pubout, open(priName, 'w') as priout: pubout.write('{} {} {}'.format(prime, gen2, e2)) priout.write('{} {} {}'.format(prime, gen2, randNum)) return def getPrime(bits=8): ''' Generates a prime from using the Miller- Rabin function. The prime number is of the bit size specified by the 'bits' var ''' prime: int = getrandbits(bits) while not is_prime(n=prime, num_of_randos=rands): prime = getrandbits(bits) return prime def generator(k=8): ''' expects some value k that is a bit size. This function inversely creates a prime from a hardcoded generator 2 rather than the other way. ''' prime: int = 0 # not prime and fails Miller-Rabin fast while not is_prime(n=prime, num_of_randos=rands): qrime: int = 0 # reset q # number below is hard coded to allow for (gen mod p = 2) while qrime%12 != 5: qrime = getPrime(bits=(k-1)) prime = 2*qrime + 1 # if isPrime then ensures strength return prime # Encryption related functions ------------------------------------------------------- def encrypt(e1, e2, prime, plaintext): ''' Description here ''' ciphers: list = [''] * 2 randomNum = random.randint(a=0, b=(prime-1)) ciphers[0] = fast_exp(base=e1, exponent=randomNum, mod=prime) # Using: # ab mod n = [(a mod n)(b mod n)] mod n # ciphers[1] = (plaintext * e2**randomNum) % prime # becomes... factor1 = plaintext % prime factor2 = fast_exp(base=e2, exponent=randomNum, mod=prime) ciphers[1] = (factor1*factor2) % prime return ciphers # Decryption related functions ------------------------------------------------------- def decrypt(ciphers, prikey, prime): ''' This takes in a dictionary of two cipher integer, c1 and c2, along with a private key int and a prime number. It uses the shortcut equation in the project spec to recombine c1 and c2 into the original int for the plaintext ''' # Need to do ((c1**(p-1-d) mod p) * (c2 mod p)) mod p c1, c2 = int(ciphers['c1']), int(ciphers['c2']) prime, prikey = int(prime), int(prikey) factor1: int = fast_exp(base=c1, exponent=(prime-1-prikey), mod=prime) factor2: int = c2 % prime plaintext: int = (factor1*factor2) % prime return plaintext # Procedure related functions -------------------------------------------------------- def str_to_int(word): ''' takes in a string and takes every char from it, converts it to Ascii, concats it to the low end of the previous character. The final value is an integer. ''' total: int = 0 for c in word: # print(ord(c)) total = total<<8 ^ ord(c) # print(total) return total def int_to_str(num): word: str = '' mask: int = 0xFF while num != 0: c = mask & num # print('c={}'.format(chr(c))) num = num>>8 word = chr(c) + word # print('word='+word+'|') return word def main(args): inputfile: str = args.inputfile outputfile: str = args.outputfile keyfile: str = args.keyfile key: bool = args.genkey e: bool = args.e_flag d: bool = args.d_flag if key: gen_key() elif e: # Reading key from file and plaintext from input file with open(keyfile, 'r') as pubin, open(inputfile, 'r') as fin: pubkey: list = pubin.read().split() plainT: str = fin.read() # print('public key data is...') #DEBUG # print('p:', pubkey[0], #DEBUG # '\tg:', pubkey[1], #DEBUG # '\te2:', pubkey[2]) #DEBUG # print('plain:\n'+ plainT) #DEBUG # chunk plain text into words of size n | is defined at top words = [plainT[i : i+wordSize] for i in range(0, len(plainT), wordSize)] # print(words) #DEBUG with open(outputfile, 'w') as fout: fout.write('') # to erase the output file with open(outputfile, 'a') as fout: # Where the actual call for encrypt w/ one word at a time for word in words: wordInt = str_to_int(word) # print(wordInt) #DEBUG ciphers = encrypt(int(pubkey[1]), int(pubkey[2]), int(pubkey[0]), wordInt) # print('c1: {}, c2: {}'.format(ciphers[0],ciphers[1])) fout.write('{} {}\n'.format(ciphers[0],ciphers[1])) elif d: # Reading key from file with open(keyfile, 'r') as privin:#, open(inputfile, 'r') as fin: prikey: list = privin.read().split() # Reading ciphers from input file into a master list cipherlist = list() ciphers = {'c1' : 0, 'c2' : 0} fin = open(inputfile, 'r') for line in fin: ciphers['c1'], ciphers['c2'] = line.split() cipherlist.append(ciphers.copy()) # print(ciphers['c1'], ciphers['c2']) #DEBUG # for dic in cipherlist: #DEBUG # print(dic) # print('p:', prikey[0], #DEBUG # '\tg:', prikey[1], # '\te2:', prikey[2]) with open(outputfile, 'w') as fout: fout.write('') with open(outputfile, 'a') as fout: for ciphers in cipherlist: # print('c1:{},c2:{}'.format(ciphers['c1'], ciphers['c2'])) wordInt = decrypt(ciphers=ciphers, prikey=prikey[2], prime=prikey[0]) # print('pInt:{}'.format(wordInt)) word = int_to_str(wordInt) # print(word+'|') fout.write(word) else: print('ERROR: no options specified') return if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-e', '--e_flag', action='store_true', help='encrypt input file') parser.add_argument('-d', '--d_flag', action='store_true', help='decrypt input file') parser.add_argument('-in', '--inputfile', help='specify input file') parser.add_argument('-out', '--outputfile', help='specify output file') parser.add_argument('-k', '--keyfile', help='specify key file') parser.add_argument('-genkey', '--genkey', action='store_true', help='generates keys') args = parser.parse_args() if (args.e_flag and args.d_flag) or (args.genkey and (args.e_flag or args.d_flag)): #give error print('ERROR: conflicting flags active') exit() main(args) exit()
34cf5dbfbf40c3d7f1a3965383ee549a21c74fb2
Zerobitss/Python-101-ejercicios-proyectos
/practica88.py
4,169
3.9375
4
def plato(): menu_principal = ['Pizzas','Pasta','Ensaladas'] menu_eleccion = [menu_pizzas(), menu_pasta(), menu_ensalada()] opcion_menu = int(input("1.-Pizzas\n2.-Pasta\n3.-Ensaladas\nQue deseas comer hoy: ")) if (opcion_menu <= len(menu_principal)): print(f"Tu eleccion fue: {menu_principal[opcion_menu-1]}") iterador(menu_eleccion[opcion_menu-1]) menu_eleccion = menu_eleccion[opcion_menu-1] plato = menu_principal[opcion_menu-1] return plato, menu_eleccion def plato_sabor(): menu_eleccion = plato() iterador(menu_eleccion[1]) opcion_plato = int(input("Que deseas pedir: ")) for j in range(len(menu_eleccion[1])): if opcion_plato == j: print(f"Pediste una {menu_eleccion[0]}, {menu_eleccion[1][opcion_plato-1]}") sabor = menu_eleccion[1][opcion_plato-1] pedido = menu_eleccion[0]+", "+ sabor return pedido def pedido_extra(): adicional = extras() extra = [] if adicional is True: adicionales = int(input("\n1.-Aperitivos\n2.-Salsas\nQue deseas agregar: ")) if adicionales == 1: extra = menu_extras() elif adicionales == 2: extra = menu_extra_salsas() iterador(extra) print("Estos son los ingredientes que puedes agregar: ") return extra else: return extra def pedido_final(): pedido = plato_sabor() extra = pedido_extra() pedido_final = {} if any(extra): opcion_extra = int(input("Cual deseas agregar: ")) for k in range(len(extra)): if opcion_extra == k: suplemento = extra[opcion_extra-1] pedido_final[pedido] = suplemento for key, value in pedido_final.items(): print(f"Pediste: {key}, con Extra: {value}") else: print(f"Su plato es: {pedido}") def iterador(menu_impresion): for i, j in enumerate(menu_impresion,1): print(i, j) def menu_pizzas(): pizzas = ['Margarita','Napolitana','Roqueford','Tonno','Prosciutto','Funghi','Capricciosa','Roana','Franmy','Quatro Stagioni', 'Del Padrone','Piamontesa','Vegetal','Pietro','Minano','Quatro Quesos','Speciale','Pazza','Marinera','Picante', 'Veneciana','Panfli','Brava','Hawaiana','Calzone','Carbonara','Ciao','Serrana','Mediterranea','Barbacoa','Bambino', 'Mexicana','Cosa Nostra','Antidepresiva'] return pizzas def menu_pasta(): pasta = ['Berenjenas Gratinadas','Lasagna Bolognesa','Tortellini Bolognesa','Tortellini Roquefort','Tortellini Carbonara', 'Canalones Clasicos','Canalones Carbonara','Macarrones Bolognesa','Macarrones Carbonara','Espaguetis Bolognesa', 'Espaguetis Carbonara','Espaguetis al Roquefort','Tallarines Carbonara','Tallarines al Roquefort','Ravioli Bolognesa', 'Ravioli Carbonara','Ravioli al Roquefort'] return pasta def menu_ensalada(): ensaladas = ['Simple','Mixta','Capricciosa','Ciao','Roquefort','Ensalada de Pasta','Tribecca'] return ensaladas def menu_extras(): suplemento_pizza = ['Atún','Anchoa','Aceitunas','Esparragos','Pimiento Verde','Carne Picada','Papas Fritas','Maiz','Mozzarella', 'Bacon','Almeja','Alcachofa','Jamón York','Parmesano','Jamón Serrano','Chorizo','Alcaparras','Salami Picante' ,'Huevo','Pimiento Morrón','Pepperoni','Poño','Salsa Barbacoa','Roquefort','Salsa Carbonara', 'Piña','Cebolla','Mejillones','Champiñón','Gruyere','Tabasco','Tomate Natural'] return suplemento_pizza def menu_extra_salsas(): salsas = ['Barbacoa','Brava','Roquefort','Mayonesa','Alioli','Rosa','Ketchup', 'Salsa Brava'] return salsas def extras(): extra = str(input("Deseas añadir algun extra a su pedido?: (si/no) ")) extra = extra.lower() if extra == 'si': return True elif extra == 'no': return False else: print("Escriba una opcion correcta") def run(): print("🍕Bienvenido a la pizzeria🍕") pedido_final() if __name__ == "__main__": run()
5d9f81915ee5b355e49e86ed96da385f40c81280
Zerobitss/Python-101-ejercicios-proyectos
/practica47.py
782
4.1875
4
""" Escribir un programa que almacene el diccionario con los créditos de las asignaturas de un curso {'Matemáticas': 6, 'Física': 4, 'Química': 5} y después muestre por pantalla los créditos de cada asignatura en el formato <asignatura> tiene <créditos> créditos, donde <asignatura> es cada una de las asignaturas del curso, y <créditos> son sus créditos. Al final debe mostrar también el número total de créditos del curso. """ def run(): cursos = { "Matematica": 6, "Fisica": 4, "Quimica": 5 } for i, j in cursos.items(): print(f"Asignaturas: {i}", end="/ Tiene ") print(f"Creditos: {j}") total = sum(cursos.values()) print(f"El total de credito del curso son: {total}") if __name__ == "__main__": run()
31536f9c78af3c4974ffd1fe1239547faf27a07b
Zerobitss/Python-101-ejercicios-proyectos
/practica65.py
358
3.921875
4
""" 3: Con operadores logicos, determina si una cadena de texto ingresada por el usuario tiene una longitud mayor o igual a 3 y a su vez es menor a 10. (true o false) """ def run(): texto = str(input("Ingresa un texto: ")) if len(texto) >= 3 and len(texto) < 10: print(True) else: print(False) if __name__ == "__main__": run()
f6c650389a5589fd1889af109d49878ea4f31f6e
Zerobitss/Python-101-ejercicios-proyectos
/practica97.py
987
3.859375
4
class Persona(): def __init__(self, apellidoPat, apellidoMat, nom): self.apellidoPaterno = apellidoPat self.apellidoMaterno = apellidoMat self.nombres = nom def mostrarNombre(self): txt = "{0}, {1}, {2}" return txt.format(self.apellidoPaterno, self.apellidoMaterno, self.nombres) class Estudiante(Persona): def __init__(self, apellidoPat, apellidoMat, nom , pro): #Se declaran los atributos a heredad super().__init__(apellidoPat, apellidoMat, nom) #Se hace la declaracion de los atributos heredados self.profesion = pro #El argumento "pro" se refiere a la profesion esto quiere decir que solamente va a poder ser utilizado en esta clase, # ya que esta clase es para estudiante, del mismo modo pudiesemos crear otra clase para trabajador y colocar el puesto de trabajo estudiante1 = Estudiante("Rojas", "Ollarves", "Jose", "Ingenieria de Sistemas") print(estudiante1.mostrarNombre()) print(estudiante1.profesion)
1c07f5f093217d0818bda345ebc9f1dec853394a
Zerobitss/Python-101-ejercicios-proyectos
/practica6.py
722
3.828125
4
""" Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas. """ def run(): login = str(input("Ingresa tu correo: ")) passw = str("sixsamurai123*") password = str(input("Escribe tu contraseña: ")) password = password.lower() if passw == password: print(f"Usuario introducido coincide perfectamente: {login}") print(f"La contraseña introducida coincide perfectamente: {passw}") else: print("Contraseña incorrecta") if __name__ == '__main__': run()
34aa36caf907e6334d2dcb3e7b1594fd736007f3
Zerobitss/Python-101-ejercicios-proyectos
/practica42.py
427
4.0625
4
""" Escribir un programa que almacene en una lista los siguientes precios, 50, 75, 46, 22, 80, 65, 8, y muestre por pantalla el menor y el mayor de los precios. """ def run(): precios = [50, 75, 46, 22, 80, 65, 8] precios.sort() minimo = min(precios) maximo = max(precios) print(f"El menor de los precios es: {minimo}") print(f"El mayor de los precios es: {maximo}") if __name__ == '__main__': run()
669612375d9e39154bbfc4273767fe19fe313dbc
Zerobitss/Python-101-ejercicios-proyectos
/practica62.py
256
3.8125
4
""" 5)Aqui hay un texto que esta alreves, es un alumno, que tiene una nota del examen.¿Como podemos darlo vuelta y verlo normalmente? texto = "zaid luar, 10" """ def run(): texto = "zaid luar, 10" print(texto[::-1]) if __name__ == "__main__": run()
c58beab76a386453584e334a14ca93b9979c8bd5
Zerobitss/Python-101-ejercicios-proyectos
/practica4.py
383
4.03125
4
""" Escribir un programa que pregunte al usuario su edad y muestre por pantalla si es mayor de edad o no. """ def run(): print("🤗Bienvenido al programa para saber si eres mayor o no 😁") edad = int(input("Ingresa tu edad: ")) if edad >= 18: print("Si eres mayor de edad") else: print("No eres mayor de edad") if __name__ == '__main__': run()
975c2263afb1696d97671eba3731aa05349ee3f4
Zerobitss/Python-101-ejercicios-proyectos
/practica1.py
1,668
4.125
4
""" Una juguetería tiene mucho éxito en dos de sus productos: payaso y muñeca. Suele hacer venta por correo y la empresa de logística les cobra por peso de cada paquete así que deben calcular el peso de los payasos y muñecas que saldrán en cada paquete a demanda. Cada payaso pesa 112 g y la muñeca 75 g. Escribir un programa que lea el número de payasos y muñecas vendidos en el último pedido y calcule el peso total del paquete que será enviado. """ def run(): peso_payaso = 112 peso_muneca = 75 menu_inicio =(""" 🤖Bienvenido a la jugeteria👾 Los jugetes disponibles en este momento son: 1.- Payasos, costo = 100$, su peso es de 112g 2.- Muñeca, costo = 90$, su peso es de 75g """) print(menu_inicio) while True: menu = int(input(""" Que jugetes deseas comprar? 1.- Payaso 2.- Muñeca 3.- Terminar compra 4.- Salir Eligue tu opcion: """)) if menu == 1: payaso_cant = int(input("Escribe la cantidad de payasos que quieres comprar: ")) peso_payaso *= payaso_cant elif menu == 2: muneca_cant = int(input("Escribe la cantidad de muñeca que quieres comprar: ")) peso_muneca *= muneca_cant elif menu == 3: pedido = peso_payaso + peso_muneca print(f"Gracias por su compra, el peso total de su pedido es: {pedido}g") print("Espero volverte a ver pronto por aqui, hasta luego 😁") return False elif menu == 4: print("Espero volverte a ver pronto por aqui, hasta luego 😁") return False if __name__ == '__main__': run()
96cffff7188de858043be7752354bdf527b6042c
Zerobitss/Python-101-ejercicios-proyectos
/practica85.py
1,985
4.46875
4
""" Escribir una función que simule una calculadora científica que permita calcular el seno, coseno, tangente, exponencial y logaritmo neperiano. La función preguntará al usuario el valor y la función a aplicar, y mostrará por pantalla una tabla con los enteros de 1 al valor introducido y el resultado de aplicar la función a esos enteros. """ """ calculadora, seno coseno tangete import math s = input("Escribe un numero: ") #Captura un numero s1 = float (s) #Transforma a flotante s2 = math.radians(s1) #Transforma a radianes x = math.radians() y = math.radians() z = math.radians() a = math.exp() # Calculo exponencial b = math.log() #Logaritmo neperiano print(math.sin(s2)) print(math.sin(x)) print(math.cos(y)) print(math.tan(z)) """ import math def calculadora_cientifica(numero): for i in range(1, numero + 1): if i % 2 == 0: print(f"Numeros pares: {i}") opcion = int(input(""" 1.- Seno 2.- Coseno 3.- Tangente 4.- Exponencial 5.- Logaritmo neperiano Que tipo de calculo deseas realizar: """)) for j in range(1, numero+ 1): calculos(opcion, j) def calculos(opcion, valor): if opcion == 1: valor = math.radians(valor) print("Calculo de Seno", end=" ") return print(math.sin(valor)) elif opcion == 2: valor = math.radians(valor) print("Calculo de Coseno", end=" ") return print(math.cos(valor)) elif opcion == 3: valor = math.radians(valor) print("Calculo de Tangente", end = " ") return print(math.tan(valor)) elif opcion == 4: print("Calculo Exponencial") return print(math.exp(valor)) elif opcion == 5: print("Calculo Logaritmo natural") return print(math.log(valor)) else: print("Opcion incorrecta") def run(): print("Calculadora cientifica") numero = int(input("Ingresa un numero: ")) calculadora_cientifica(numero) if __name__ == "__main__": run()
c61148bd558bcf40610b0bdaed53f3d2bb3876a3
Zerobitss/Python-101-ejercicios-proyectos
/practica67.py
702
3.875
4
""" (1)Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña hasta que introduzca la contraseña correcta. """ def run(): while True: password = str(input("Ingresa tu contraseña: ")) re_password = str(input("Repite tu contraseña: ")) if password == re_password: print(f"Tu contraseña coinciden: {re_password}") print("Bienvenido!") return False else: print(f"Tu contraseñas no son iguales, tu primera contraseña fue: ({password})\t Tu segunda contraseña fue: ({re_password}), porfavor intenta de nuevo") if __name__ == "__main__": run()
645d14de2df189107ae1b0d6562e4e83e984d0ec
DiogoNeves/PyAlgo
/algos/stack.py
862
3.6875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- from algos import CollectionException, Collection, UNLIMITED class StackException(CollectionException): pass class Stack(Collection): def __init__(self, capacity=-1): if capacity == 0 or capacity < UNLIMITED: raise StackException( 'Capacity must be an int > 0 or Stack.UNLIMITED') self._capacity = capacity self._stack = [] def push(self, item): if self.full(): raise StackException('already full') else: self._stack.append(item) def pop(self): if self.empty(): raise StackException('already empty') else: return self._stack.pop() def empty(self): return len(self._stack) == 0 def full(self): return len(self._stack) == self._capacity
23c8d095e97226e3c7558de15a692abda0bd0e01
kunal-singh786/basic-python
/ascii value.py
219
4.15625
4
#Write a program to perform the Difference between two ASCII. x = 'c' print("The ASCII value of "+x+" is",ord(x)) y = 'a' print("The ASCII value of "+y+" is",ord(y)) z = abs(ord(x) - ord(y)) print("The value of z is",z)
3fe0e5c3fd08074abc2d7b60f5b799b5b0acb538
kunal-singh786/basic-python
/loop hackerrank.py
176
4.09375
4
'''Task Read an integer . For all non-negative integers , print . See the sample for details''' if __name__ == '__main__': n = int(input()) for i in range(n): print(i**2)
4afe44be49a57421c502423cc9f0226df2e07a8c
kunal-singh786/basic-python
/5a1.py
280
3.8125
4
mobile = ['nokia','samsung','vivo','oppo','redmi'] x = type(mobile) print(x) string = ' '.join(mobile) print(string) def check_vow(string,vowels): final = [each for each in string if each in vowels] print(len(final)) print(final) vowels = "AaEeIiOoUu" check_vow(string,vowels);
cd87777649d836dbd3f48b638f645f6060041ca1
kunal-singh786/basic-python
/bus ticket generate.py
1,036
3.9375
4
print(" Jotti Travelers") bus_no =int(input("Enter the bus number(Gurugram to Other= 35, Other to Gurugram= 36)=")) name = str(input("Name:-")) age = int(input("Age:-")) gender = str(input ("Gender:-")) source = str(input("Source:-")) des = str(input("Destination:-")) rate = int(input("Enter the distance between source and destination(for Amritsar = 3 , for kanpur = 5,for Patna =8 and For kolkata 12)=")) cost = rate*100 if cost == 300: print(" You want to pay",cost," and this ticket is valid only for Gurugram to Amritsar") elif cost == 500: print(" You want to pay",cost," and this ticket is valid only for Gurugram to Kanpur") elif cost == 800: print(" You want to pay",cost," and this ticket is valid only for Gurugram to Patna ") elif cost == 1200: print(" You want to pay",cost," and this ticket is valid only for Gurugram to Kolkata ") print("Note:- if you travel without taking ticket than you want to pay the fine upto 5000 and for any clarification please contact our helpline number 9789926551")
43aaeac595fb07f69b90c5e481e3197582b0f65e
rafaelacarnaval/uri-online-judge
/Revisão.py
434
4
4
print("Hello World!") first_name = "Rafaela" last_name = "Carnaval" age = 25 height = 1.60 print("Olá, %s %s. Eu tenho %d anos e %.2f de altura" %(first_name, last_name, age, height)) first_name = input("Nome:\n") last_name = input("Sobrenome:\n") age = int(input("Idade:\n")) height = float(input("Altura:\n")) print ("Olá, meu nome é %s %s. Eu tenho %d anos e %.2f de altura." %(first_name, last_name, age, height))
8ca4c0008691ecaac718f1f2610c62816f75523c
rafaelacarnaval/uri-online-judge
/uri_1021.py
376
3.859375
4
n = float(input()) notas = [100,50,20,10,5,2] moedas = [1,0.50,0.25,0.10,0.05,0.01] print("NOTAS:") for nota in notas: quantidade = n / nota print("%d nota(s) de R$ %d.00" %(quantidade, nota)) n = n % nota print("MOEDAS:") for moeda in moedas: quantidade = n / moeda print("%d moeda(s) de R$ %.2f" %(quantidade, moeda)) n = round((n % moeda),2)
40889d762e49b20ff541207f16649b5cadcebbcb
e998/CS550
/13dog_class.py
2,210
4.09375
4
# 10/25/2018 """ Properties - breed - size - color - name * - home - food/diet - owner - tricks - energy * - hunger * - thirst - happiness """ """ Methods - walk - eat * - sleep * - play fetch - roll over - bark - bite - follow owner - sit """ # name with capital letter and with singular class Seal: ### CONSTRUCTOR # initalizes properties and sets up the dog object # self refers to the class # though self is passed around, it does not need to be referenced # name, hunger, energy - local variables def __init__(self, name, hunger, energy, ): # scale can be determined (keep in mind, not written down - out of 10) self.hunger = hunger self.energy = energy # self.happiness = happiness # names for all dogs not the same self.name = name ### METHODS / FUNCTIONS def eat(self, amount): statusEat = "" if self.hunger > 0: # hunger: 0 is full, 10 is very hungry self.hunger -= 1 # energy: 0 is tired, 10 is energetic self.energy += amount statusEat = self.name + " just ate a delicious meal!" else: statusEat = self.name + " refused to eat because they are full!" return statusEat def sleep(self, time): statusSleep = "" if self.energy <= 10-time: self.energy += time statusSleep = self.name + " just had a wonderful nap!" else: statusSleep = self.name + " is not tired and doesn't want to sleep!" return statusSleep def stats(self): return "\nName: " + self.name + "\nEnergy: " + str(self.energy) + "\nHunger: " + str(self.hunger) # want to keep class as flexible as possible, don't ask for input or print things in a class sealname = input("What do you want to name your seal?\n") # seal1 is more complicated variable type # Seal is class, and seal1 & seal2 are objects # objects like the house being printed using the blueprint, which is the class seal1 = Seal(sealname, 5, 2) seal2 = Seal("Enhy", 3, 9) # while True is an infinite loop while True: print(seal1.stats()) print(seal2.stats()) choice = input("\n\nWhat do you want to do?\n") if choice == "Eat": print(seal1.eat(2)) print(seal2.eat(2)) elif choice == "Sleep": print(seal1.sleep(2)) print(seal2.sleep(2)) else: print("Your seal can't do that!")
f34edf98143ba9e7eea0ec02bd93db3465943fe6
e998/CS550
/card.py
681
3.859375
4
# 11/1/2018 class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): # create local variable rank, don't want to permanently change the number of the rank rank = self.rank suit = self.suit if rank == 1: rank = "Ace" elif rank == 11: rank = "Jack" elif rank == 12: rank = "Queen" elif rank == 13: rank = "King" else: rank = str(self.rank) if suit == "h": suit = "Hearts" elif suit == "d": suit = "Diamonds" elif suit == "c": suit = "Clubs" elif suit == "s": suit = "Spades" return str(rank) + " of " + str(suit) # suit: h, d, c, s # rank: 2-10, J, Q, K, A - 1-13 #__string__
9b18e28d9b8defa2507779a95d69d7d59e4c0576
e998/CS550
/w3montecarlowalk.py
3,006
4.40625
4
# 1/10/2019 # CS550 Class/HW Winter # Monte Carlo Walk & Dart Simulation # Answer: 22 blocks (Longest walk where you'll be within walking distance at least 50% of the time) """ Solution Explantion: In the Monte Carlo simulation, for different lengths between the values of 0 and 30, the user goes on random walks for a certain number of trials. The user always moves one step along the x-axis or the y-axis for each step of the walk. Each step is randomly generated by the use of the list forwardback and the random variable moveXorY. After the user completes a random walk, the program checks if the user is within 4 units of the starting point (0,0). If the trip left the user close enough to walk home (within 4), 1 is added to variable "walk". After each walk, the beginning coordinates are reset. The length of the walk, A, is saved to the variable "blocks" if the user is within walking distance at least 50% of the time. """ """ Monte Carlo Simulations Research: - What are they? Monte Carlo simulations are computerized mathematical techniques that account for risk. They provide the user a range of all possible outcomes and probabilities. - What can they be used for? Monte Carlo simulations can be used for risk management in a variety of fields including, but not limited to: finance, manufacturing engineering, energy, and project management. - How do they work? Monte Carlo simulations create probability distributions by building models of potential outcome values. Recalculating values over and over again enable them to accurately depict all possibilities. """ """ Sources: random.choice & random.uniform - https://docs.python.org/2/library/random.html """ ### Imports import random from random import * import math from math import * ### Monte Carlo Simulation x,y = 0,0 # home coordinates trips = 10000 blocks = 0 forwardback = [1.0, -1.0] # person moves forward one, back one, up one, or down one for each step for A in range(40): walk = 0 for i in range(trips): # trials to find average for one block value for j in range(A): # walking away from home once moveXorY = randint(0,1) # person moves along x-axis or y-axis if moveXorY == 0: x += choice(forwardback) elif moveXorY == 1: y += choice(forwardback) if abs(x) + abs(y) <= 4: walk += 1 # reset x and y coordinates after each trip x,y = 0,0 if walk/trips >= 50/100: blocks = A # print(str(walk) + "/" + str(trips)) # result: walks about 80% of the time (800/1000) for 10 blocks print(blocks) ### Dart Simulation trials = 100000 circle = 0 for i in range(trials): # number of times dart is thrown x,y = uniform(-1,1), uniform(-1,1) if (x**2 + y**2 < 1): circle += 1 # number of trials where the dart makes it within the circle num = (circle*4)/trials print(num) """ Observations about output of dart simulation: As the number of trials, or times the dart is thrown at the target, increases, the number, num, gets closer to pi and oscillates less. """
8173f27556c3d20308fed59059819a509afaf083
marianraven/estructuraPython
/ejercicio7.py
287
4.15625
4
#Escribir un programa que pregunte el nombre del usuario por consola y luego imprima #por pantalla la cadena “Hola <nombre_usuario>”. Donde <nombre_usuario> es el #nombre que el usuario introdujo. nombreIngresado= str(input('Ingrese su nombre:')) print('Hola......', nombreIngresado)
9452b77f4adca6f96525f9a2a3623e5a019111a6
marianraven/estructuraPython
/ejercicio17.py
518
3.984375
4
#Escribir un programa que pida un número natural n al usuario e imprima por pantalla #la suma de los números naturales de 1 hasta n. Por ejemplo para n = 5, la salida debe #ser: #1 + 2 + 3 + 4 + 5 = 15 #Nota: Hacerlo de dos formas, usando y sin usar la ecuación: #F ( n ) = ∑ i= #i= 1 #n ( n+1 ) #2 entrada= int(input('Ingrese un número natural:')) nulo=0 while nulo< entrada: nulo+=1 aux=0 aux+=1 print(entrada,'entrada--------') print(aux,'suma----------') print(nulo,'nulo-----------')
e26dd47bed2da8fd37db2411b242636426f50d12
ShrutiBalla9/ShrutiBalla7
/fileoperation.py
595
3.859375
4
#writing in file with open("text.txt","w",encoding='utf-8')as f: f.write("hello") f.close() f = open("text.txt","r") print(f.read()) #reading file f = open('text.txt','r',encoding='utf-8') print(f.read()) #closing opened file f = open("text.txt","r",encoding='utf-8') print(f.read()) f.close() #reading file f = open('text.txt','r') print(f.read()) #writing in file f = open("text.txt","w") f.write("fileoperation") f.close() f = open("text.txt","r") print(f.read()) #closing opened file f = open("text.txt","r") print(f.read()) f.close()
d62fb1c8e99fc0208f21f782bb8b1ea04ff0899b
ShrutiBalla9/ShrutiBalla7
/operators.py
389
4.0625
4
# Arithmetic operator x=20 y=10 print("\n 20+10=",x+y) print("\n 20-10=",x-y) print("\n 20*10=",x*y) print("\n 20%10=",x%y) print("\n 20/10=",x/y) print("\n 20**10=",pow(x,y)) #comparison operators print("x>y",x>y) print("x<y",x<y) print("x==y",x==y) print("x!=y",x!=y) #logical operator print("x and y is",x and y) print("x or y is",x or y) print("x not y is", not y)
729fe090ac9756c25199f1f2ab6dd3e98a65ff51
jbascunan/Python
/1.Introduccion/16.metodos_estaticos.py
557
3.6875
4
class Circulo: # variable de clase pi = 3.1416 # METODO ESTATICO @staticmethod def pi2(): return 3.14 # CONSTRUCTOR def __init__(self, radio): self.radio = radio self.perimetro = 4 # METODO DE INSTACIA def suma(self): return "suma" circulo1 = Circulo(1) circulo2 = Circulo(2) # obtiene valor de variable de clase print(Circulo.pi) # obtiene valor de metodo de clase print(Circulo.pi2()) # obtiene valor de variable de objeto (instancia) print(circulo1.perimetro) print(circulo1.pi)
de2c66cc004eae8ba588f8e775fc8266e9867df5
jbascunan/Python
/1.Introduccion/2.diccionarios.py
966
4.3125
4
# las llaves puede ser string o enteros diccionario = { 'a': 1, 'b': 2, 'c': 3 } # diccionario de llave enteros diccionario1 = { 1: "nada", 2: "nada2" } print(diccionario1) # agregar clave/valor diccionario['d'] = 4 # modifica valor diccionario['e'] = 5 # si la llave existe se actualiza sino la crea print(diccionario) # obtener valor por la clave valor = diccionario['a'] print(valor) # obtener valor por defecto cuando no existe llave valor2 = diccionario.get('z', False) print(valor2) # eliminar llave/valor segun llave del diccionario['e'] print(diccionario) # obtener objeto iterable llaves = diccionario.keys() # obtiene llaves print(llaves) llaves1 = list(diccionario.keys()) # obtiene objeto como lista print(llaves1) valores = diccionario.values() # obtiene valores print(valores) valores2 = list(valores) # obtiene objeto como lista print(valores2) # unir diccionarios diccionario.update(diccionario1) print(diccionario)
cf1b2e8a4454c28033a86f08ffda2544c4018078
jbascunan/Python
/1.Introduccion/18.herencia.py
730
3.609375
4
class Animal: # clase abuelo @property def terrestre(self): return "animal" class Felino(Animal): # clase padre hereda de Animal @property def garras_retractiles(self): return True def cazar(self): print("cazando") class Gato(Felino): # hereda de Felino def gato_cazador(self): self.cazar() class Jaguar(Felino): # hereda de Felino @classmethod def prueba(cls): print("prueba") @staticmethod def prueba2(): print("prueba static") gato = Gato() jaguar = Jaguar() print(gato.gato_cazador()) print(jaguar.garras_retractiles) print(jaguar.terrestre) # obtiene propiedad de clase herencia abuelo Jaguar.prueba() Jaguar.prueba2()
1026cedd32de74a4318e5fd7dea6e77a5a39ad8a
tbchamp/UWCSE403-Recipe-Reader
/web/cgi/allrecipes_scraper.py
8,155
3.53125
4
#!/usr/bin/python #print page header print "Content-type: text/html" print "" import cgi import cgitb; import htmllib import httplib import re import sys import unicodedata import urllib import urllib2 from urlparse import urlparse from BeautifulSoup import BeautifulSoup #function for unescaping string for printing at the end def unescape(s): if not s: return s p = htmllib.HTMLParser(None) p.save_bgn() p.feed(s) return p.save_end() # function for makeing sure input is valid URL def exists(site, path): conn = httplib.HTTPConnection(site) conn.request('HEAD', path) response = conn.getresponse() conn.close() return response.status == 200 ## Code starts running here ############################# #verify parameters is given form = cgi.FieldStorage() value_input = form.getvalue("input") value_meal = form.getvalue("meal") value_category = form.getvalue("category") value_keyword = form.getvalue("keyword") if not (form.has_key("input") and form.has_key("meal") and form.has_key("category") and form.has_key("keyword")): print "error: bad input" sys.exit() else: input = cgi.escape(value_input) meal = cgi.escape(value_meal) category = cgi.escape(value_category) keyword = cgi.escape(value_keyword) print "<a href=\"http://cubist.cs.washington.edu/projects/12wi/cse403/r/upload.php\"><--BACK</a>" print "<h1> Input: </h1>" print "<p> URL: " + input + " </p>" print "<p> Meal: " + meal + " </p>" print "<p> Category: " + category + " </p>" print "<p> Keyword: " + keyword + " </p>" # verify the page exists url = urlparse(input) if not exists(url.netloc, url.path): print "URL is invalid" sys.exit() #beautiful soup the page #this library makes elements of the given webpage searchable by html attributes #this allows us to find the different parts of the recipe page = urllib2.urlopen(input) soup = BeautifulSoup(page) #pull out the parts of the page we want: ##title title = soup.find('span', attrs={"class":"itemreviewed"}) if title: title = title.text ##picture picture = soup.find('img', attrs={"class":"rec-image photo"}) if picture: picture = picture['src'] ##description temp = soup.findAll('div', attrs={"class":"author-info rounded-box"}) for t in temp: temp2 = t.findAll('div', attrs={"class":"plaincharacterwrap", "style":"clear:right;"}) for i in temp2: description = i if description: description = description.text ##prep time prep_time = soup.findAll('span', attrs={"class":"prepTime"}) if prep_time: prep_time = prep_time[0].nextSibling.nextSibling.text ##cook time cook_time = soup.findAll('span', attrs={"class":"cookTime"}) if cook_time: cook_time = cook_time[0].nextSibling.nextSibling.text ##ready time ready_time = soup.findAll('span', attrs={"class":"totalTime"}) if ready_time: ready_time = ready_time[0].nextSibling.nextSibling.text ##yield info yield_info = soup.find('span', attrs={"class":"yield yieldform"}) if yield_info: yield_info = yield_info.text ##ingredients ingredients = soup.findAll('li', attrs={"class":"plaincharacterwrap ingredient"}) if ingredients: temp = ingredients ingredients = [] for ingredient in temp: ingredients.append( ingredient.text ) #re.escape(ingredient.text).replace("\\", "") ) ##directions directions = soup.findAll('span', attrs={"class":"plaincharacterwrap break"}) if directions: temp = directions directions = [] for direction in temp: directions.append(direction.text) """ ##notes ##not used currently by RecipeReader notes = soup.find('div', attrs={"id":"ctl00_CenterColumnPlaceHolder_recipe_rptNotes_ctl01_noteContainer"}) if notes: temp = notes.contents notes = "" for note in temp: notes += ' '.join(note.string.split()) """ ##calories calories = soup.find('span', attrs={"class":"calories"}) if calories: calories = re.sub("[^0-9\.]", "", calories.text) ##fat fat = soup.find('span', attrs={"class":"fat"}) if fat: fat = re.sub("[^0-9\.]", "", fat.text) ##cholesterol cholesterol = soup.find('span', attrs={"class":"cholesterol"}) if cholesterol: cholesterol = re.sub("[^0-9\.]", "", cholesterol.text) #add title to keywords keywords = [] if title: title_temp = unescape(title) #depreciated since shelex.split does not work properly #title_parts = shlex.split(title_temp) title_parts = [t.strip('"') for t in re.findall(r'[^\s"]+|"[^"]*"', title_temp)] for t_part in title_parts: keywords.append(t_part) if keyword: temp_keywords = [t.strip('"') for t in re.findall(r'[^\s"]+|"[^"]*"', keyword)] for tmp_key in temp_keywords: keywords.append(tmp_key) # print the keywords print "<p> keywords: " for word in keywords: print " \"" + word + "\" " print "</p>" #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Send to php scripts to input to database print "<h1> Upload to DataBase Results: </h1>" db_url1 = 'http://cubist.cs.washington.edu/projects/12wi/cse403/r/php/add_recipe.php' db_url2 = 'http://cubist.cs.washington.edu/projects/12wi/cse403/r/php/addtorecipe.php' # 1. add overview info values = { 'name' : title, 'rating' : '5', 'description' : description, 'preptime' : prep_time, 'cooktime' : cook_time, 'readytime' : ready_time, 'yield' : yield_info, 'calories' : calories, 'fat' : fat, 'cholesterol' : cholesterol, 'meal' : meal, 'category' : category, 'img_loc' : picture } data = urllib.urlencode(values) req = urllib2.Request(db_url1, data) response = urllib2.urlopen(req) the_page = response.read() if the_page == "Recipe Create Failed!": print the_page sys.exit() id = int(the_page) # 2. add ingredients for ingredient in ingredients: if ingredient[0] != '&': values = { 'type' : 'ingredient', 'text' : ingredient, 'recipe_id' : id } data = urllib.urlencode(values) req = urllib2.Request(db_url2, data) response = urllib2.urlopen(req) the_page = response.read() if the_page != "Ingredient Inserted": print the_page #sys.exit() # 3. add directions count = 0 for direction in directions: count += 1 values = { 'type' : 'direction', 'text' : direction, 'order' : count, 'recipe_id' : id } data = urllib.urlencode(values) req = urllib2.Request(db_url2, data) response = urllib2.urlopen(req) the_page = response.read() if the_page != "Direction Inserted": print the_page #sys.exit() # 4. add keywords for key in keywords: values = { 'type' : 'keyword', 'phrase' : key, 'recipe_id' : id } data = urllib.urlencode(values) req = urllib2.Request(db_url2, data) response = urllib2.urlopen(req) the_page = response.read() if the_page != "Keyword Inserted": print the_page #sys.exit() # done print "<p> Upload to database complete </p>" #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # print results print "<p> </p>" print "<h1> Scraped Data: </h1>" print "<p> </p>" print "<p> title: " if title: print unescape(title) else: print "<NONE>" print " </p>" print "<p> </p>" print "<p> picture: " if picture: print unescape(picture) else: print "<NONE>" print " </p>" print "<p> </p>" print "<p> description: " if description: print unescape(description) else: print "<NONE>" print " </p>" print "<p> </p>" print "<p> prep_time: " if prep_time: print unescape(prep_time) else: print "<NONE>" print " </p>" print "<p> </p>" print "<p> cook_time: " if cook_time: print unescape(cook_time) else: print "<NONE>" print " </p>" print "<p> </p>" print "<p> ready_time: " if ready_time: print unescape(ready_time) else: print "<NONE>" print " </p>" print "<p> </p>" print "<p> yield_info: " if yield_info: print unescape(yield_info) else: print "<NONE>" print " </p>" print "<p> </p>" print "<p> ingredients: </p>" print "<ul>" for ingredient in ingredients: if ingredient[0] != '&': print "<li> " + unescape(ingredient) + " </li>" print "</ul>" print "<p> </p>" print "<p> directions: </p>" print "<ol>" for direction in directions: print "<li> " + unescape(direction) + " </li>" print "</ol>" print "<p> </p>" """ print "<p> notes: " + unescape(notes) + " </p>" print "<p> </p>" """ print "<p> calories: " + unescape(calories) + " </p>" print "<p> </p>" print "<p> fat: " + unescape(fat) + " </p>" print "<p> </p>" print "<p> cholesterol: " + unescape(cholesterol) + " </p>"
6439616147683c7d01b8ce2814276118ae362c89
ulises1229/NURBS-Python_Examples
/ex_curve04.py
1,143
3.671875
4
# -*- coding: utf-8 -*- """ Examples for the NURBS-Python Package Released under MIT License Developed by Onur Rauf Bingol (c) 2017 """ from nurbs import Curve as ns from nurbs import utilities as utils from matplotlib import pyplot as plt # Create a NURBS curve instance curve = ns.Curve() # The full circle with NURBS curve.read_ctrlptsw("data/CPw_Curve4.txt") curve.degree = 2 # Use a specialized knot vector curve.knotvector = [0, 0, 0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1, 1, 1] # Calculate NURBS curve points curve.evaluate_rational() # Arrange control points for plotting ctrlpts_x = [] ctrlpts_y = [] for pt in curve.ctrlpts: ctrlpts_x.append(pt[0]) ctrlpts_y.append(pt[1]) # Arrange curve points for plotting curvepts_x = [] curvepts_y = [] for pt in curve.curvepts: curvepts_x.append(pt[0]) curvepts_y.append(pt[1]) # Plot using Matplotlib plt.figure(figsize=(8, 8), dpi=96) cppolygon, = plt.plot(ctrlpts_x, ctrlpts_y, "k-.") curveplt, = plt.plot(curvepts_x, curvepts_y, "r-") plt.legend([cppolygon, curveplt], ["Control Points Polygon", "Evaluated Curve"]) plt.show() print("End of NURBS-Python Example")
f1533c7e247c3dfae9a3b416cadc90e8e471eb5b
bobyaaa/Competitive-Programming
/CCC/CCC '05 S5 Pinball Ranking.py
1,484
3.703125
4
#Run in pypy2 or TLE ;-; #Basically what we're doing here is mergesorting the list, and then counting the inversions of the mergesort. #Solution by Andrew Xing import sys n = int(sys.stdin.readline()) alist = [] for x in range(n): alist.append(int(sys.stdin.readline())) swapCount = 0 def mergeSort(alist): global swapCount if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 swap = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] > righthalf[j]: alist[k]=righthalf[j] j=j+1 swapCount = swapCount + (len(lefthalf) - i) else: alist[k]=lefthalf[i] i=i+1 k=k+1 """ if lefthalf[i] < righthalf[j] or lefthalf[i] == righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 swapCount = swapCount + (len(lefthalf) - i) k=k+1 """ while i < len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 mergeSort(alist) print("%.2f" % float((swapCount + n)/float(n)))
b1b664af153b13d978314cb61c5e656901daf1be
bobyaaa/Competitive-Programming
/CCC/CCC '03 S1 - Snakes and Ladders.py
646
3.6875
4
win = False counter = 1 while win == False: roll = input() if roll == 0: break counter = counter + roll if counter == 9: counter = 34 elif counter == 40: counter = 64 elif counter == 54: counter = 19 elif counter == 67: counter = 86 elif counter == 90: counter = 48 elif counter == 99: counter = 77 elif counter == 100: print "You are now on square " + str(counter) win = True break elif counter > 100: counter = counter - roll else: counter = counter print "You are now on square " + str(counter) if roll == 0: print "You Quit!" else: print "You Win!"
b766cd78c2fe2e777e563ebca005b1fa180e890d
bobyaaa/Competitive-Programming
/CCC/CCC '04 J3 Smile with Similes.py
283
3.84375
4
adj = input() noun = input() adjliszt = [] nounliszt = [] for x in range(adj): adjliszt.append(raw_input()) for x in range(noun): nounliszt.append(raw_input()) for x in range(len(adjliszt)): for y in range(len(nounliszt)): print adjliszt[x] + " as " + nounliszt[y]
3b1d0f4f464f06987564946eb720995f5f7e9b28
bobyaaa/Competitive-Programming
/Bruce/Bruno and Pumpkins.py
1,363
3.65625
4
#Solution by Andrew Xing import sys n = input() t = input() dp_but_not_really = [input() for x in range(n)] dp_but_not_really.sort() #We sort our dp. This is because we just want to find the optimal solutions. Say we have -4 -3 -2 1 8. Why would you try #to compute the distance (if you want three pumpkins) for -4, -3, 1, when clearly -4, -3, -2, will give you a better answer. #All the optimal answers come from indexes subsequent to one another. So like (-4, -3, -2), (-3, -2, 1), (-2, 1, 8). #Those are the only things we need to check, and we can run this in O(N) time. result = 10000 for x in range(t-1, n): #Find the minimum of the furthest negative and furthest positive #Use it to compute minimum distance #If there is only positive, or only negative, then we just use the furthest positive/furthest negative #as our distance. if dp_but_not_really[x-(t-1)] <= 0 and dp_but_not_really[x] <= 0: save = abs(dp_but_not_really[x-(t-1)]) elif dp_but_not_really[x-(t-1)] >= 0 and dp_but_not_really[x] >= 0: save = abs(dp_but_not_really[x]) else: minimum = min(abs(dp_but_not_really[x-(t-1)]), dp_but_not_really[x]) if minimum == abs(dp_but_not_really[x-(t-1)]): save = minimum*2 + dp_but_not_really[x] else: save = minimum*2 + abs(dp_but_not_really[x-(t-1)]) if save < result: result = save print result
61ee175839674d678f7ad5e54dbc68e9698d80fe
bobyaaa/Competitive-Programming
/Other/Rabbit Girls.py
297
3.71875
4
rabbit_girls = input() group = input() if group > rabbit_girls: print group - rabbit_girls elif group == rabbit_girls: print 0 else: remainder = rabbit_girls % group if remainder == 0: print 0 elif remainder > float(group/2): print group - remainder else: print remainder
87a6d5e514a8d472b5fe429ddf28190fb3e38547
EddieMichael1983/PDX_Code_Guild_Labs
/RPS.py
1,514
4.3125
4
import random rps = ['rock', 'paper', 'scissors'] #defining random values for the computer to choose from user_choice2 = 'y' #this sets the program up to run again later when the user is asked if they want to play again while user_choice2 == 'y': #while user_choice2 == y is TRUE the program keeps going user_choice = input('Choose rock, paper, or scissors: ') #the computer asks the user for their choice choice = random.choice(rps) #the computer randomly chooses rock, paper, or scissors print(f'The computer chose {choice}.') if user_choice == 'rock' and choice == 'rock': print('Tie') elif user_choice == 'rock' and choice == 'paper': print('Paper covers rock, you lose.') elif user_choice == 'rock'and choice == 'scissors': print('Rock smashes scissors, you win.') elif user_choice == 'paper' and choice == 'rock': print('Paper covers rock, you win.') elif user_choice == 'paper' and choice == 'paper': print('Tie') elif user_choice == 'paper' and choice == 'scissors': print('Scissors cuts paper, you lose.') elif user_choice == 'scissors' and choice == 'rock': print('Rock smashes scissors, you lose.') elif user_choice == 'scissors' and choice == 'paper': print('Scissors cuts paper, you win.') elif user_choice == 'scissors' and user_choice == 'scissors': print('Tie') #determines who won and tells the user user_choice2 = input('Do you want to play again?: y/n ')
e1bd7675cbe0ca378fcc5799262bdb1796e53716
EddieMichael1983/PDX_Code_Guild_Labs
/functions.py
536
3.859375
4
#functions.py #illustrates the difference between print and return def noisy_add(num1, num2): print(f"ADDING {num1} AND {num2}!!! :D") return num1 + num2 #return leaves behind what it points at def bad_add(num1, num2): print(num1 + num2) #print just shows what it prints and leaves none behind def return4(in_thing): print(in_thing) return 4 def print4(in_thing): print(4) return in_thing var1 = return('ab') + return4('cd') #running line 10 - 12 ab cd print var1 8
698c8d06b87bda39846c76dff4ddb1feb682cf4f
ManchuChris/MongoPython
/PrimePalindrome/PrimePalindrome.py
1,739
4.1875
4
# Find the smallest prime palindrome greater than or equal to N. # Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1. # For example, 2,3,5,7,11 and 13 are primes. # Recall that a number is a palindrome if it reads the same from left to right as it does from right to left. # # For example, 12321 is a palindrome. # Example 1: # Input: 6 # Output: 7 # # Example 2: # Input: 8 # Output: 11 # # Example 3: # Input: 13 # Output: 101 #The method checking if it is prime. # def CheckIfPrime(N): # if N > 1: # for i in range(2, N // 2): # if N % i == 0: # return False # # return True #The method checking if it is palindrome # def reverseString(list): # return list[::-1] # # def CheckIfPalindrome(list): # reversedlist = reverseString(list) # if reversedlist == list: # return True # return False # # #print(CheckIfPrime(9)) # print(CheckIfPalindrome("1")) # Solution: class Solution: def primePalindrome(self, N: int) -> int: N = N + 1 while N > 0: if self.CheckIfPrime(N): if self.CheckIfPalindrome(str(N)): return N break N = N + 1 else: N = N + 1 def CheckIfPrime(self, N): if N > 1: for i in range(2, N // 2): if N % i == 0: return False return True def reverseString(self, list): return list[::-1] def CheckIfPalindrome(self, list): reversedlist = self.reverseString(list) # reversedlist = reversed(list) if reversedlist == list: return True return False
56ed66d12f06498a53c9be533a829efdd00d2bd6
ManchuChris/MongoPython
/AddLinkedList/AddLinkedList.py
1,918
3.890625
4
# Given two numbers represented by two linked lists, write a function that returns the sum list. # The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. # Also, not allowed to use explicit extra space (Hint: Use Recursion) class node: def __init__(self, value=None): self.value = value self.next = None class linkedList: def __init__(self): self.head = None def push(self, value): new_node = node(value) new_node.next = self.head self.head = new_node def addTwoLists(self, firstList, secondList): Prev = None temp = None carry = 0 while firstList is not None or secondList is not None: firstValue = 0 if firstList is None else firstList.value secondValue = 0 if secondList is None else secondList.value Sum = carry + firstValue + secondValue carry = 1 if Sum >= 10 else 0 Sum = Sum if Sum < 10 else Sum % 10 temp = node(Sum) if self.head is None: self.head = temp else: Prev.next = temp Prev = temp if firstList is not None: firstList = firstList.next if secondList is not None: secondList = secondList.next if carry > 0: temp.next = node(carry) def printList(self): temp = self.head while temp: print(temp.value), temp = temp.next first = linkedList() second = linkedList() first.push(6) first.push(4) first.push(9) first.push(5) first.push(7) print("First List is "), first.printList() second.push(4) second.push(8) print("\nSecond List is "), second.printList() finalList = linkedList() finalList.addTwoLists(first.head, second.head) print("\nsum List is "), finalList.printList()
11f5d71093cf9d5c00d06f88875d9ec00ed0ee5c
aduqu3/calculadora_metodos
/PyQt5/funciones.py
6,974
3.5625
4
import sys from math import * import numpy as np from numpy import log as ln # ============================ REPLACE CHARACTERS ON STRING INI =================== # reemplazar simbolos en la cadena de caracteres para poderse utilizar en el metodo simpson 1/3 def string_replace(string): replacements = { '^': '**', } for old, new in replacements.items(): string = string.replace(old, new) return string # ============================ REPLACE CHARACTERS ON STRING FIN =================== # ============================ SIMPSON 1/3 INI =================== #SIMPSON 1/3 #@ n: numero de x #@ a y b los intervalos de la integral #@ f: La funcion a integrar def simpson_13_cal(f, a, b, n): # evaluar una funcion en x def fx(x, f): return eval(f) f = string_replace(f) # print(f) #calculamos h h = (b - a) / n #Inicializamos nuestra varible donde se almacenara las sumas suma = 0.0 #hacemos un ciclo para ir sumando las areas for i in range(1, n): #calculamos la x #x = a - h + (2 * h * i) x = a + i * h # si es par se multiplica por 4 if(i % 2 == 0): suma = suma + 2 * fx(x, f) #en caso contrario se multiplica por 2 else: suma = suma + 4 * fx(x, f) #sumamos los el primer elemento y el ultimo suma = suma + fx(a, f) + fx(b, f) #Multiplicamos por h/3 rest = suma * (h / 3) #Retornamos el resultado # print(rest) return rest # ============================ SIMPSON 1/3 FIN =================== # ============================ TRAPECIOS INI =================== # metodo trapecios def trapecios(func, a, b, m): def funcx(x, f): return eval(f) func = string_replace(func) print(func) h = (b-a)/float(m) s = 0 n = 0 a_evaluado = 0 b_evaluado = 0 for i in range(1,m): n = a + (i*h) n_evaluado = funcx(n, func) #evalua n en la funcion descrita s = s + n_evaluado a_evaluado = funcx(a, func) #evalua a en la funcion descrita, lo mismo con b en la siguiente linea b_evaluado = funcx(b, func) result = h/2 * (a_evaluado + 2*s + b_evaluado) return result # ============================ TRAPECIOS FIN =================== # ============================ BISECCION INI =================== def bisection(f,a,b,N): def fx(x,f): return eval(f) f = string_replace(f) if fx(a,f)*fx(b,f) >= 0: print("Bisection method fails.") return None a_n = a b_n = b for n in range(1,N+1): m_n = (a_n + b_n)/2 f_m_n = fx(m_n,f) if fx(a_n,f)*f_m_n < 0: a_n = a_n b_n = m_n elif fx(b_n, f)*f_m_n < 0: a_n = m_n b_n = b_n elif f_m_n == 0: print("Found exact solution.") print(m_n) return m_n else: print("Bisection method fails.") return None return (a_n + b_n)/2 # ============================ BISECCION FIN =================== # ============================ SIMPSON 3/8 INI =================== def simpson_38(f,x0,xf,n): def fx(x,f): return eval(f) f = string_replace(f) # Integracion mediante Simpson 3/8 n = n - n%3 # truncar al multiplo de 3 mas cercano if n<=0: n = 1 h = (xf-x0)/n x = x0 suma = 0 for j in range(n//3): suma += fx(x, f) + 3.*fx(x+h, f) + 3.*fx(x+2*h, f) + fx(x+3*h, f) x += 3*h r=(3.*h/8)*suma return r # ============================ SIMPSON 3/8 FIN =================== # ============================ FALSA POSICION INI =================== def falsa_posicion(f,a,b,tolera): def fx(x,f): return eval(f) f = string_replace(f) tramo = abs(b-a) while not(tramo<=tolera): fa = fx(a,f) fb = fx(b,f) c = b - fb*(a-b)/(fa-fb) fc = fx(c,f) cambia = np.sign(fa)*np.sign(fc) if (cambia > 0): tramo = abs(c-a) a = c else: tramo = abs(b-c) b = c raiz = c return raiz # ============================ FALSA POSICIOM FIN =================== # ============================ NEWTON-RAPHSON INI =================== def newton_raphson(f,df,x0,tolera): def fx(x, f): return eval(f) def dfx(x, df): return eval(df) f = string_replace(f) df = string_replace(df) tabla = [] tramo = abs(2*tolera) xi = x0 while (tramo>=tolera): fxi = fx(xi, f) dfxi = dfx(xi,df) xnuevo = xi - fxi/dfxi tramo = abs(xnuevo-xi) tabla.append([xi,xnuevo,tramo]) xi = xnuevo # convierte la lista a un arreglo. tabla = np.array(tabla) n = len(tabla) return ("raiz",xi,"con error de", tramo) # ============================ NEWTON-RAPHSON FIN =================== # ================================ SECANTE INI ========================= def secante(f, xa, tolera): # evaluar funcion en x def fx(x, f): return eval(f) # tabla secante def secante_tabla(f,xa,tolera): dx = 4*tolera xb = xa + dx tramo = dx tabla = [] while (tramo>=tolera): fa = fx(xa, f) fb = fx(xb, f) xc = xa - fa*(xb-xa)/(fb-fa) tramo = abs(xc-xa) tabla.append([xa,xb,xc,tramo]) xb = xa xa = xc tabla = np.array(tabla) return (tabla) # reemplazar caracteres en la funcion... f = string_replace(f) tabla = secante_tabla(f,xa,tolera) n = len(tabla) raiz = tabla[n-1,2] np.set_printoptions(precision=4) # print('[xa ,\t xb , \t xc , \t tramo]') # for i in range(0,n,1): # print(tabla[i]) return ("raiz en: ", raiz) # ================================ SECANTE FIN ========================= # ================================ PUNTO FIJO INI ========================= def punto_fijo(func, approx, tol, n): def fx(x, f): return eval(f) func = string_replace(func) for i in range(0, n): p = fx(approx, func) if abs(p-approx) < tol: return p approx = p return "Method failed after {} iterations".format(n) # ================================ PUNTO FIJO FIN ========================= # ================================ TIPOS DE ERRORES INI ========================= def error_verdadero(valor_verdadero,valor_aproximado): return ("El error verdadero es : ",valor_verdadero-valor_aproximado ) def error_relativo(valor_real,valor_aproximado): valor_absoluto= valor_real-valor_aproximado return ("El error relativo es : ",valor_absoluto/valor_real) def error_aproximado(aproxi_anterior,aproxi): return ("El error de aproximación es : ",((aproxi-aproxi_anterior)/aproxi)*100) # ================================ TIPOS DE ERRORES FIN =========================
3f40aa3e28b189fabc48fad78347448ddb2ad706
l8g/graph
/Graph/Dfs/Path.py
1,198
3.546875
4
import sys sys.path.insert(0, "..") from Expression.Graph import Graph class Path(): def __init__(self, g : Graph, s, t): self._g = g self._s = s; self._t = t; self._visited = [False] * g.v() self._pre = [-1] * g.v() self._pre[s] = s self._dfs(s) def _dfs(self, u): self._visited[u] = True if u == self._t: return True for v in self._g.adj(u): if not self._visited[v]: self._pre[v] = u if self._dfs(v): return True return False def connected(self): return self._visited[self._t] def path(self): res = [] if not self.connected(): return res curr = self._t while curr != self._s: res.insert(0, curr) curr = self._pre[curr] res.insert(0, self._s) print(self._visited) return res if __name__ == "__main__": g = Graph("g.txt") path = Path(g, 0, 5) print("0->5: ", path.path()) path2 = Path(g, 0, 1) print("0->5: ", path2.path())
ebe3d0b8c5d85eb504e9c68c962c1fa8343eab3b
aartis83/Project-Math-Painting
/App3.py
2,137
4.1875
4
from canvas import Canvas from shapes import Rectangle, Square # Get canvas width and height from user canvas_width = int(input("Enter the canvas width: ")) canvas_height= int(input("Enter the canvas height: ")) # Make a dictionary of color codes and prompt for color colors = {"white": (255, 255, 255), "black": (0, 0, 0)} canvas_color = input("Enter the canvas color (white or black): ") # Create a canvas with the user data canvas = Canvas(height=canvas_height, width=canvas_width, color=colors[canvas_color]) while True: shape_type = input("what would you like to draw? Enter quit to quit.") # Ask for rectangle data and create rectangle if user entered 'rectangle' if shape_type.lower() == "rectangle": rec_x = int(input("Enter x of the rectangle: ")) rec_y = int(input("Enter y of the rectangle: ")) rec_width = int(input("Enter the width of the rectangle: ")) rec_height = int(input("Enter the height of the rectangle: ")) red = int(input("How much red should the rectangle have? ")) green = int(input("How much green should the rectangle have? ")) blue = int(input("How much blue should the rectangle have? ")) # Create the rectangle r1 = Rectangle(x=rec_x, y=rec_y, height=rec_height, width=rec_width, color=(red, green, blue)) r1.draw(canvas) # Ask for square data and create square if user entered 'square' if shape_type.lower() == "square": sqr_x = int(input("Enter x of the square: ")) sqr_y = int(input("Enter y of the square: ")) sqr_side = int(input("Enter the side of the square: ")) red = int(input("How much red should the square have? ")) green = int(input("How much green should the square have? ")) blue = int(input("How much blue should the square have? ")) # Create the square s1 = Square(x=sqr_x, y=sqr_y, side=sqr_side, color=(red, green, blue)) s1.draw(canvas) # Break the loop if user entered quit if shape_type == 'quit': break canvas.make('canvas.png')
370e818c299774fd85ed8e467cacd8acfdff4b7d
anotherLostKitten/william_lu
/util/db_utils.py
498
3.625
4
import sqlite3 import urllib.request import json def getType(weather): '''uses weather info to get corresponding list of pokemon types''' print(weather) DB_FILE = "app.db" db = sqlite3.connect(DB_FILE) c = db.cursor() db.text_factory = str command = "SELECT data.type FROM data WHERE data.weather = \'" + weather.lower() + "\'" c.execute(command) results = c.fetchall() ptype = results[0][0].split(",") if len(results) > 0 else ["normal"] return ptype
35f51add924f454421a261899ee75e900fe1d1b7
rashed091/Algorithm-and-Data-structures
/DynamicProgramming/coin-change.py
305
3.890625
4
def change_count(S, n): m = len(S) table = [0 for _ in range(n+1)] table[0] = 1 for i in range(m): for j in range(S[i], n + 1): table[j] += table[j - S[i]] return table[n] if __name__ == "__main__": arr = [1, 2, 3] n = 5 print(change_count(arr, n))
876bc23bafaa9526d7cc54bf71cccaeb7992e57b
rashed091/Algorithm-and-Data-structures
/Queue/queue.py
431
3.796875
4
class Queue: def __init__(self): self._items = [] def is_empty(self): return self._items == [] def enqueue(self, item): self._items.insert(0, item) def dequeue(self): self._items.pop() def size(self): return len(self._items) if __name__ == "__main__": queue = Queue() queue.enqueue(1) queue.enqueue(10) queue.enqueue(100) print(queue.size())
4c34a47b1b291d3d267cf0ebd9b18f0c3501d508
rashed091/Algorithm-and-Data-structures
/Queue/palindrome.py
285
3.734375
4
from collections import deque def is_palindrome(chars): char_deque = deque(chars) while len(char_deque) > 1: first = char_deque.popleft() last = char_deque.pop() if first != last: return False return True print(is_palindrome('radar'))
27d1c5e77ebc24edd8f50c96f7c1aba313eb3ae4
fraserjamieson/static_-dynamic_testing
/part_2_code/tests/card_game_tests.py
1,219
3.984375
4
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.cards= [] # define card1 and card2 objects based on the Card class and respective instance variables self.card_4 = Card("Spades", 4) self.cards.append(self.card_4) self.card_ace = Card("Spades", 1) self.cards.append(self.card_ace) self.card_9 = Card("Hearts", 9) self.cards.append(self.card_9) self.card_game = CardGame() # complete this file first and write a test for each function def test_deck_has_ace_true(self): self.assertEqual(True, self.card_game.check_for_ace(self.card_ace)) def test_deck_has_ace_false(self): self.assertEqual(False, self.card_game.check_for_ace(self.card_9)) def test_for_highest_card_1(self): self.assertEqual(self.card_9, self.card_game.highest_card(self.card_9, self.card_4)) def test_for_highest_card_2(self): self.assertEqual(self.card_9, self.card_game.highest_card(self.card_4, self.card_9)) def test_total_cards(self): self.assertEqual("You have a total of 14", self.card_game.cards_total(self.cards))
660655e0af55d67073a42fb1170164f1554fa54d
IBRAR21/IntroToProg-Python
/Assigment05_IBRAR.py
3,886
3.84375
4
# ------------------------------------------------------------------------ # # Title: Assignment 05 # Description: Working with Dictionaries and Files # When the program starts, load each "row" of data # in "ToDoList.txt" into a python Dictionary. # Add the each dictionary "row" to a python list "table" # ChangeLog (Who,When,What): # RRoot,1.1.2030,Created started script # IBRAR,02.16.2021,Added code to complete assignment # ------------------------------------------------------------------------ # # -- Data -- # # declare variables and constants objFile = "ToDoList.txt" # An object that represents a file dicRow = {} # A row of data separated into elements of a dictionary {Task,Priority} lstRow = [] # A list of rows to create dictionary lstTable = [] # A list that acts as a 'table' of rows strChoice = "" # Capture the user option selection strTask = "" # Capture task input from user StrPriority = "" # Capture priority input from user strRemove = "" # Capture task to remove from user strMenu = """ Menu of Options 1 - Show current data 2 - Add a new task. 3 - Remove an existing task. 4 - Save Data to File 5 - Exit Program """ # A menu of user options # -- Processing -- # # Step 1 - When the program starts, load the any data you have # in a text file called ToDoList.txt into a python list of dictionaries rows (like Lab 5-2) taskFile = open(objFile, "r") for row in taskFile: lstRow = row.split("|") # Returns a list! dicRow = {"Task": lstRow[0].strip(), "Priority": lstRow[1].strip()} lstTable.append(dicRow) taskFile.close() # -- Input/Output -- # # Step 2 - Display a menu of choices to the user while (True): print(strMenu) strChoice = str(input("Which option would you like to perform? [1 to 5] - ")) print() # Step 3 - Show the current items in the table if (strChoice.strip() == '1'): print("Below is the current list of tasks: \n") print("Task","|","Priority") for row in lstTable: print(row["Task"],"|",row["Priority"]) print() continue # Step 4 - Add a new item to the list/Table elif (strChoice.strip() == '2'): strTask = input("Please enter a task: ") strPriority = input("Please assign a priority to the task [High, Medium or Low]: ") dicRow = {"Task": strTask.title(), "Priority": strPriority.title()} lstTable.append(dicRow) print("\nThe task, ",strTask.strip(), ", has been added to the table.\n", sep="") continue # Step 5 - Remove an item from the list/Table based on its name elif (strChoice.strip() == '3'): print("Here are the tasks currently in the table: ") print() for row in lstTable: print(row["Task"]) strRemove = input("\nPlease enter the task that you would like to remove: ") countRemove = 0 for row in lstTable: if row["Task"].lower() == strRemove.lower(): lstTable.remove(row) countRemove += 1 print("\nThe task, ",strRemove.strip(), ", has been removed from the table.\n", sep="") if countRemove == 0: print("\nThe task, ",strRemove.strip(), ", is not one of the tasks in the table.\n", sep="") continue # Step 6 - Save tasks to the ToDoList.txt file elif (strChoice.strip() == '4'): taskFile = open(objFile, "w") for row in lstTable: taskFile.write(row["Task"]+ "|" + row["Priority"] + "\n") taskFile.close() print("\n All tasks have been saved to the file.\n") continue # Step 7 - Exit program elif (strChoice.strip() == '5'): print("\nThank you and GoodBye!") break # and Exit the program
5b12da7ef3dd2f4eb9c36183897d14cf7cadf0bc
fangrin08/python-primer
/second.py
345
3.953125
4
import math some_text = "1a2b3c4d" def is_letter(texts): if texts in "abcdefg": return True else: return False def extract_letters(text): s = "" for c in text: if is_letter(c): s = s + c print("partial = " + s) else: print(c + " is a number!") return s letters = extract_letters(some_text) print("FINAL = " + letters)
7f021755ec5991c20b69e6eae0dd0967d3c55904
malcolmgreaves/pyprocut
/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/utils.py
3,136
3.640625
4
import logging import os import shutil from pathlib import Path from typing import Sequence, Optional, Tuple, Any def make_logger(name: str, log_level: int = logging.INFO) -> logging.Logger: """Create a logger using the given :param:`name` and logging level. """ if name is None or not isinstance(name, str) or len(name) == 0: raise ValueError("Name must be a non-empty string.") logger = logging.getLogger(name) logger.setLevel(log_level) logging.basicConfig( format="%(asctime)s %(levelname)s [%(name)s] - %(message)s", ) return logger def filename_wo_ext(filename: str) -> str: """Gets the filename, without the file extension, if present. """ return os.path.split(filename)[1].split(".", 1)[0] def program_init_param_msg( logger: logging.Logger, msg: Sequence[str], name: Optional[str] = None, log_each_line: bool = False, ) -> None: """Pretty prints important, configurable values for command-line programs. Uses the :param:`logger` to output all messages in :param:`msg`. If :param:`log_each_line` is true, then each message is applied to `logger.info`. Otherwise, a newline is inserted between all messages and they are all logged once. If :param:`name` is supplied, then it is the first logged message. If there is no name and the function is logging all messages at once, then a single newline is inserted before the mass of messages. """ separator: str = max(map(len, msg)) * "-" if log_each_line: logger.info(separator) if name is not None: logger.info(name) for line in msg: logger.info(line) logger.info(separator) else: if name: starting = f"{name}\n" else: starting = "\n" logger.info(starting + "\n".join([separator] + list(msg) + [separator])) def evenly_space(name_and_value: Sequence[Tuple[str, Any]]) -> Sequence[str]: """Pads the middle of (name,value) pairs such that all values vertically align. Adds a ':' after each name (first element of each tuple). """ if len(name_and_value) == 0: return [] max_name_len = max(map(lambda x: len(x[0]), name_and_value)) vs = [] for name, value in name_and_value: len_spacing = max_name_len - len(name) spacing = " " * len_spacing vs.append(f"{name}: {spacing}{value}") return vs def ensure_write_path(output_filepath: Path) -> None: """Ensures that the supplied path is a writeable file: raises an Error if not. """ if output_filepath.is_dir(): raise ValueError(f"Output filepath is a directory: {output_filepath}") if output_filepath.is_file(): os.remove(str(output_filepath)) output_filepath.mkdir(parents=True, exist_ok=True) output_filepath.rmdir() output_filepath.touch() def ensure_output_dir(output_dir: Path) -> None: """Ensures that there is a clean, empty directory at the supplied path. """ if output_dir.is_dir(): shutil.rmtree(str(output_dir)) output_dir.mkdir(parents=True, exist_ok=True)
c7a71766c0e273939c944342abd04ad7c6043f51
MrLawes/quality_python
/12_不推荐使用type来进行类型检查.py
2,031
4.4375
4
""" 作为动态性的强类型脚本语言,Python中的变量在定义的时候并不会指明具体类型,Python解释器会在运行时自动进行类型检查并根据需要进行隐式类型转换。按照Python的理念,为了充分利用其动态性的特征是不推荐进行类型检查的。如下面的函数add(),在无需对参数进行任何约束的情况下便可以轻松地实现字符串的连接、数字的加法、列表的合并等多种功能,甚至处理复数都非常灵活。解释器能够根据变量类型的不同调用合适的内部方法进行处理,而当a、b类型不同而两者之间又不能进行隐式类型转换时便抛出TypeError异常。 """ def add(a, b): return a + b """ 不刻意进行类型检查,而是在出错的情况下通过抛出异常来进行处理,这是较为常见的方式。但实际应用中为了提高程序的健壮性,仍然会面临需要进行类型检查的情景。那么使用什么方法呢?很容易想到,使用type()。内建函数type(object)用于返回当前对象的类型,如type(1)返回<type 'int'>。因此可以通过与Python自带模块types中所定义的名称进行比较,根据其返回值确定变量类型是否符合要求。 """ class UserInt(int): def __init__(self, val=0): self._vala = int(val) n = UserInt(1) print(type(n)) """ 这说明type()函数认为n并不是int类型,但UserInt继承自int,显然这种判断不合理。由此可见基于内建类型扩展的用户自定义类型,type函数并不能准确返回结果。 """ """ 因此对于内建的基本类型来说,也许使用type()进行类型检查问题不大,但在某些特殊场合type()方法并不可靠。那么究竟应怎样来约束用户的输入类型从而使之与我们期望的类型一致呢? 答案是:如果类型有对应的工厂函数,可以使用工厂函数对类型做相应转换,如list(listing)、str(name)等,否则可以使用isinstance()函数来检测 """
0f4da657552e172025f3b4ede87a233ffdafab51
MrLawes/quality_python
/19_有节制地使用from...import语句.py
4,555
3.78125
4
""" Python提供了3种方式来引入外部模块:import语句、from...import...及__import__函数。 其中较为常见的为前面两种,而__import__函数与import语句类似, 不同点在于前者显式地将模块的名称作为字符串传递并赋值给命名空间的变量。在使用import的时候注意以下几点: ·一般情况下尽量优先使用import a[插图]形式,如访问B时需要使用a.B的形式。· 有节制地使用from a import B形式,可以直接访问B。·尽量避免使用from a import *, 因为这会污染命名空间,并且无法清晰地表示导入了哪些对象。 """ """ 为什么在使用import的时候要注意以上几点呢?在回答这个问题之前先来简单了解一下Python的import机制。 Python在初始化运行环境的时候会预先加载一批内建模块到内存中,这些模块相关的信息被存放在sys.modules中。 读者导入sys模块后在Python解释器中输入sys.modules.items()便可显示所有预加载模块的相关信息。 当加载一个模块的时候,解释器实际上要完成以下动作: 1)在sys.modules中进行搜索看看该模块是否已经存在,如果存在,则将其导入到当前局部命名空间,加载结束。 2)如果在sys.modules中找不到对应模块的名称,则为需要导入的模块创建一个字典对象,并将该对象信息插入sys.modules中。 3)加载前确认是否需要对模块对应的文件进行编译,如果需要则先进行编译。 4)执行动态加载,在当前模块的命名空间中执行编译后的字节码,并将其中所有的对象放入模块对应的字典中。 我们以用户自定义的模块为例来看看sys.modules和当前局部命名空间发生的变化。 在Python的安装目录下创建一个简单的模块testmodule.py: """ import sys print(dir()) from datetime import MAXYEAR print(dir()) print(sys.modules['datetime']) print(id(sys.modules['datetime'])) print(id(MAXYEAR)) # print(id(sys.modules['MAXYEAR'])) # error """ 了解完import机制,我们再来看看对于from a import ...无节制的使用会带来什么问题。 """ """ (1)命名空间的冲突. 来看一个例子。假设有如下3个文件:a.py,b.py及importtest.py, 其中a和b都定义了add()函数,当在import test文件中同时采用from...import...的形式导入add的时候, import test中起作用的到底是哪一个函数呢? 文件a.py如下: def add(): print('add in module A') 文件b.py如下: def add(): print('add in model B') 文件importtest.py如下: from a import add from b import add add() 从程序的输出“add in module B”可以看出实际起作用的是最近导入的add(), 它完全覆盖了当前命名空间之前从a中导入的add()。 在项目中,特别是大型项目中频繁地使用from a import ...的形式会增加命名空间冲突的概率从而导致出现无法预料的问题。 因此需要有节制地使用from...import语句。一般来说在非常明确不会造成命名冲突的前提下, 以下几种情况下可以考虑使用from...import语句: 1)当只需要导入部分属性或方法时。 2)模块中的这些属性和方法访问频率较高导致使用“模块名.名称”的形式进行访问过于烦琐时。 3)模块的文档明确说明需要使用from...import形式, 导入的是一个包下面的子模块,且使用from...import形式能够更为简单和便利时。 如使用from io.drivers import zip要比使用import io.drivers.zip更方便。 """ """ (2)循环嵌套导入的问题先来看下面的例子: """ """ 先来看下面的例子: c1.py: from c2 import g def x(): pass c2.py: from c1 import x def g(): pass """ """ 无论运行上面哪一个文件都会抛出ImportError异常。 这是因为在执行c1.py的加载过程中,需要创建新的模块对象c1然后执行c1.py所对应的字节码。 此时遇到语句from c2 import g,而c2在sys.modules也不存在,故此时创建与c2对应的模块对象并执行c2.py所对应的字节码。 当遇到c2中的语句from c1 import x时,由于c1已经存在,于是便去其对应的字典中查找g, 但c1模块对象虽然创建但初始化的过程并未完成,因此其对应的字典中并不存在g对象,此时便抛出ImportError: cannot import name g异常。 而解决循环嵌套导入问题的一个方法是直接使用import语句。读者可以自行验证。 """
c047864044d2270efeef97adf40483da5cdbeced
MrLawes/quality_python
/10_充分利用Lazy evaluation的特性.py
1,057
4.25
4
""" Lazy evaluation常被译为“延迟计算”或“惰性计算”,指的是仅仅在真正需要执行的时候才计算表达式的值。 充分利用Lazy evaluation的特性带来的好处主要体现在以下两个方面: 1)避免不必要的计算,带来性能上的提升。对于Python中的条件表达式if x and y, 在x为false的情况下y表达式的值将不再计算。而对于if x or y, 当x的值为true的时候将直接返回,不再计算y的值。因此编程中应该充分利用该特性。 """ """ 2)节省空间,使得无限循环的数据结构成为可能。Python中最典型的使用延迟计算的例子就是生成器表达式了,它仅在每次需要计算的时候才通过yield产生所需要的元素。 斐波那契数列在Python中实现起来就显得相当简单,而while True也不会导致其他语言中所遇到的无限循环的问题。 """ def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b from itertools import islice print(list(islice(fib(), 5)))
7ef3708e603ae031572167066e5044e6f24ee068
jkHaam/django
/regular_expression_test.py
305
3.5625
4
import re def validate_phone_number(number): #핸드폰 체크 if not re.match(r'^01[016789][0-9]\d{6,7}$', number): return False return True print(validate_phone_number('01012341234')) print(validate_phone_number('0101112222')) print(validate_phone_number('010111112222'))
e65f822dc56d694c6dc62b0b26fbbdb744dcc823
fahmyabida/python-basic_learning
/soal1.py
234
3.703125
4
cars = ["Toyota", "Honda", "Mitsubishi"] for car in cars: print "this is brand from", car if car == "Toyota": print " - Camry" elif car == "Honda": print " - CR-V" elif car == "Mitsubishi": print " - Pajero"
f3738fd5bf9df2a2ca93adb4c706dc28870bc8a5
amxsa/python_demo
/pythonAPI/04.set.py
281
3.84375
4
#coding:utf-8 #set无序,不重复 #set里面不能放入list set1=set([1,2,3]) #输出为{1,2,3} print(set1) set2=set([2,2,3,4]) set1.add(4) set1.remove(4) #set的交集 print(set1&set2) #set的并集 print(set1|set2) # list去重 list1 = [2, 4, 3, 4, 5] print(list(set(list1)))
431ef06eaedab40960f81efab3aaae1276f4c490
amxsa/python_demo
/pythonAPI/20.实例属性和类属性.py
811
3.6875
4
#coding:utf-8 class Student(object): name="Stu" def __init__(self,name): self.name=name s=Student("Bob") s.score=90 #实例属性 print(s.name) #类属性 print(Student.name) print("\n===================\n") #给实例绑定属性和方法 class Person(object): pass p=Person() #动态给实例绑定一个属性 p.name="Xiaohua" print(p.name) #定义一个函数作为实例方法 def set_age(self,age): self.age=age from types import MethodType #给实例绑定一个方法 p.set_age=MethodType(set_age,p) p.set_age(25) print(p.age) #给一个实例绑定的方法,对另一个实例是不起作用的 #为了给所有实例都绑定方法,可以给 class 绑定方法 def set_score(self,score): self.score=score Person.set_score=MethodType(set_score,Person) p.set_score(100) print(p.score)
d5b5a1455f0c502525b8a04df9738906d5ed9c2d
AmnesiaWu/NN
/sources/Practice1.py
494
3.703125
4
# encoding:utf-8 # class Solution: def bin_rev(self, int_input): """ :param int_input: int :return:int """ bin_input = bin(int_input) result_bin = bin_input[::-1][:-2] # 把输入的整数的二进制数翻转 result_int = int(result_bin, 2) return result_int if __name__ == '__main__': solution = Solution() int_input = eval(input("请输入一个整数:")) result = solution.bin_rev(int_input) print(result)
6f3810e4b3dae9d48fabef845b56465f3a0b7324
rebeling/monday-morning-mite
/results.py
1,072
3.671875
4
def overview(users, notes=False): for i, u in enumerate(users): print '{}. {}\n{}'.format(i, u, '-'*79) stats = users[u]['statistics'] for k in ['total entries', 'tasks', 'billable', 'references', 'time total', 'mean per entry', 'shortest entry', 'longest entry', 'different projects', 'projects']: v = stats[k] if isinstance(v, list) and len(v) > 3: print '{}:'.format(k) for w in v: print ' {}'.format(w) else: print '{}: {}'.format(k, v) if notes: print '\nNotes:' for e in users[u]['entries']: print ' * {}'.format(e['note'].encode('utf-8')) print '\n' weekly(users[u]['week']) def weekly(week): weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] for day in weekdays: print "\n{}:".format(day) for i, e in enumerate(week[day]): print " {}. {}".format(i+1, e['note'])
a9851d6286afaa894a86b3674849cd72ccc05d40
kesch9/Alg_Data_Structur_Python_Homework
/lesson_3/task1.py
375
3.75
4
# В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. x = list(range(2,100)) y = list(range(2,9)) print() rez =[] for i in x: ind = 0 for j in y: if i%j == 0: ind += 1 rez.append(ind) print(rez)
2d64b3b0f14096ea0070e04a6769ccf7abe0e8d4
kesch9/Alg_Data_Structur_Python_Homework
/lesson_1/task5.py
480
4.0625
4
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят и сколько между ними находится букв. a = ord(input("Введите первую букву ")) b = ord(input("Введите первую букву ")) a = a - ord('a') + 1 b = b - ord('a') + 1 print(f'Место первой буквы = {a}, второй = {b}') print(f'Разница = {abs(a-b)-1}')
baf96cd8bbc8142fcffb7b89a125241a62a7ee5d
kesch9/Alg_Data_Structur_Python_Homework
/lesson_3/task5.py
237
3.890625
4
# В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. x = [1, 2, -3, -25, 0] print(x.index(min(x)))
e7ba2b9d5dd01c9e8483b9296dc26f0bd1177f9e
a26703248/Arduino4Py_2021
/case02/LambdaLab.py
1,144
3.625
4
''' 作業 (利用 lambda) id = 'A123456789' 第二碼 sex = id[1] -> 1 (1: 男生, 2: 女生) 第三碼 area = id[2] -> 2 (0~5: 台灣, 6: 外國, 7: 無戶籍, 8: 港澳, 9: 大陸) 印出: 台灣男 ''' def Belonging(x): sex = "" if x == 1: sex = "男" else: sex = "女" def nation(y): country = " " if y <= 5 and y > 0: country = "台灣" country = country + sex else: dcl ={ 6: "外國", 7: "無戶籍", 8: "港澳", 9: "大陸" } country = dcl.get(y) + sex return country return nation if __name__ == "__main__": id = "A123456789" # Lambda語法 sex = int(id[1]) country = int(id[2]) sex_func = lambda x: "男" if sex == 1 else "女" country_func = lambda x: "台灣" if country <= 5 else "外國" if country == 6 else "無戶籍" if country == 7 else "港澳" if country == 8 else "大陸" print("{0}{1}".format(country_func(country), sex_func(sex))) #嵌套函式 b = Belonging(sex) print(b(country))
7e01564c4fdc1409e931404afdb51735016c81cf
a26703248/Arduino4Py_2021
/Project_Demo/OpenWeather.py
1,144
3.640625
4
# 絕對溫度 273.15 import requests import json import urllib.request import ssl # ssl不用驗證 def openWeather(): city = 'taoyuan' count = 'tw' apikey = '9843047d16e20413cf8f4203c24e5d29' url = 'https://api.openweathermap.org/data/2.5/weather?q={},{}&appid={}' \ .format(city, count, apikey) resp =requests.get(url) status_code = resp.status_code if(status_code == 200): jo = json.loads(resp.text) print(jo) main = jo['weather'][0]['main'] icon = jo['weather'][0]['icon'] temp = jo['main']['temp'] feels_like = jo['main']['feels_like'] humidity = jo['main']['humidity'] print(main, icon, temp, feels_like, humidity) return status_code, main, icon, temp, feels_like, humidity else: print('ERROR', resp.status_code) return status_code, None, None, None, None, None, def openWeatherIcon(icon): img_url = 'https://openweathermap.org/img/wn/%s@2x.png' % icon raw_data = urllib.request.urlopen(img_url).read() return raw_data if __name__ == "__main__": weather = openWeather() print(weather)
3fcd04a7dc8d8306cf4d1d9fd09a785fcc4e8b6e
MultiparameterTDAHistology/SpatialPatterningOfImmuneCells
/one_parameter_classes.py
8,896
3.515625
4
import numpy as np import matplotlib.pyplot as plt import copy import numbers class Bar(object): """A single bar, which should be contained in a Barcode""" def __init__(self, start, end, multiplicity): """Constructor. Takes start/birth, end/death, and multiplicity.""" self.start = start self.end = end self.multiplicity = int(round(multiplicity)) def __repr__(self): return "Bar(%s, %s, %d)" % (self.start, self.end, self.multiplicity) def expand(self): """Returns self.multiplicity copies of this bar, all with multiplicity 1""" return [Bar(self.start, self.end, 1)] * self.multiplicity def to_array(self): return np.array([self.start, self.end, self.multiplicity]) class Barcode(object): """A collection of bars""" def __init__(self, bars=None): if bars is None: bars = [] self.bars = bars def __repr__(self): return "Barcode(%s)" % self.bars def expand(self): return Barcode([be for b in self.bars for be in b.expand()]) def to_array(self): """Returns a numpy array [[start1, end1, multiplicity1], [start2, end2, multiplicity2]...].""" return np.array([(b.start, b.end, b.multiplicity) for b in self.bars]) """ Landscape classes """ class Landscape(object): """ A single landscape for a chosen k """ def __init__(self, index, critical_points): self.index = index self.critical_points = critical_points # an nx2 array def __repr__(self): return "Landscape(%d,%s)" % (self.index, self.critical_points) def plot_landscapes(self): """ Plots a single landscape""" n = np.shape(self.critical_points)[0] x = self.critical_points[1:n, 0] y = self.critical_points[1:n, 1] plt.plot(x, y) plt.show() def evaluate(self, xvalue): """ Returns the landscape value at a queried x value """ return np.interp(xvalue, self.critical_points[1:, 0], self.critical_points[1:, 1], left=0, right=0) # approximate data structure too # introduce plot function for individual landscape class Landscapes(object): """ Collection of non zero landscapes """ def __init__(self, landscapes=None): if landscapes is None: landscapes = [] self.landscapes = landscapes def __repr__(self): return "Landscapes(%s)" % self.landscapes def plot_landscapes(self): """ Plots the landscapes in the collection to a single axes""" for k in range(len(self.landscapes)): n = np.shape(self.landscapes[k].critical_points)[0] x = self.landscapes[k].critical_points[1:n, 0] y = self.landscapes[k].critical_points[1:n, 1] plt.plot(x, y) plt.show() # Add colormap options to plots # barcode is a barcode in the class form as in the implementation of pyrivet # the maxind is the maximal index landscape to compute - default is max non-zero landscape # introduce plot function for all landscapes at once MAXIMUM_NUMBER_OF_MEGABYTES_FOR_LANDSCAPES = 50.0 class landscape(object): """ Collection of non zero landscapes """ def __init__(self, barcode, x_values_range=None, x_value_step_size=None, y_value_max=None, maxind=None): """ Computes the collection of persistence landscapes associated to a barcode up to index maxind using the algorithm set out in Bubenik + Dlotko. :param barcode: A barcode object :param maxind: The maximum index landscape to calculate """ barcode = barcode.expand() barcode = barcode.to_array() if maxind is None: maxind = len(barcode) self.maximum_landscape_depth = maxind # Apply y-value threshold if y_value_max is not None: def max_y_value(persistence_pair): birth, death, _ = persistence_pair return (death - birth) / 2.0 barcode = filter(max_y_value, barcode) # Determine the minimum and maximum x-values for the # landscape if none are specified # Using map semantics here in case we want to exchange it for something # parallelized later if x_values_range is None: def max_x_value_of_persistence_point(persistence_pair): _, death, _ = persistence_pair return death def min_x_value_of_persistence_point(persistence_pair): birth, _, _ = persistence_pair return birth death_vector = np.array(list(map(max_x_value_of_persistence_point, barcode))) birth_vector = np.array(list(map(min_x_value_of_persistence_point, barcode))) self.x_values_range = [np.amin(birth_vector), np.amax(death_vector)] else: self.x_values_range = x_values_range # This parameter value is recommended; if it's not provided, # this calculation tries to keep the total memory for the landscape under # the threshold number of MiB if x_value_step_size is None: self.x_value_step_size = maxind * (self.x_values_range[1] - self.x_values_range[0]) * 64.0 / ( MAXIMUM_NUMBER_OF_MEGABYTES_FOR_LANDSCAPES * pow(2, 23)) else: self.x_value_step_size = x_value_step_size def tent_function_for_pair(persistence_pair): birth, death, _ = persistence_pair def evaluate_tent_function(x): if x <= (birth + death) / 2.0: return max(0, x - birth) else: return max(0, death - x) return evaluate_tent_function x_values_start, x_value_stop = self.x_values_range width_of_x_values = x_value_stop - x_values_start number_of_steps = int(round(width_of_x_values / self.x_value_step_size)) # print('nbr of step='+str(number_of_steps)) x_values = np.array(range(number_of_steps)) x_values = x_values * self.x_value_step_size + x_values_start self.grid_values = x_values def x_value_to_slice(x_value): unsorted_slice_values = np.array(list(map(lambda pair: tent_function_for_pair(pair)(x_value), barcode))) return unsorted_slice_values landscape_slices = np.array(list(map(x_value_to_slice, x_values))) if maxind > landscape_slices.shape[1]: padding = np.zeros((number_of_steps, maxind - landscape_slices.shape[1])) landscape_slices = np.hstack((landscape_slices, padding)) self.landscape_matrix = np.empty([maxind, number_of_steps]) for i in range(number_of_steps): self.landscape_matrix[:, i] = landscape_slices[i, :] if maxind <= landscape_slices.shape[1]: self.landscape_matrix = np.empty([landscape_slices.shape[1], number_of_steps]) for i in range(number_of_steps): self.landscape_matrix[:, i] = landscape_slices[i, :] # sorts all the columns using numpy's sort self.landscape_matrix = -np.sort(-self.landscape_matrix, axis=0) self.landscape_matrix = self.landscape_matrix[:maxind, :] def __repr__(self): return "Landscapes(%s)" % self.landscape_matrix def plot_landscapes(self, landscapes_to_plot=None): """ Plots the landscapes in the collection to a single axes""" if landscapes_to_plot is None: landscapes_to_plot = range(self.maximum_landscape_depth) elif type(landscapes_to_plot) is int: landscapes_to_plot = range(landscapes_to_plot) for k in landscapes_to_plot: x = self.grid_values y = self.landscape_matrix[k, :] plt.plot(x, y) plt.show() def __add__(self, other_landscape): if np.shape(self.landscape_matrix) != np.shape(other_landscape.landscape_matrix): raise TypeError("Attempted to add two landscapes with different shapes.") if self.x_values_range != other_landscape.x_values_range: raise TypeError("Attempted to add two landscapes with different ranges of x-values.") added_landscapes = copy.deepcopy(self) added_landscapes.landscape_matrix = self.landscape_matrix + other_landscape.landscape_matrix return added_landscapes def __mul__(self, multiple): # Scalar multiplication if isinstance(multiple, numbers.Number): multiplied_landscape = copy.deepcopy(self) multiplied_landscape.landscape_matrix *= multiple return multiplied_landscape # Inner product, * is element-wise multiplication else: return np.sum(self.landscape_matrix * multiple.landscape_matrix) def __sub__(self, other): return self + (-1.0) * other
3b9b8ccc58875db61691c0e4dfbd5222967c70ab
Hitthesurf/PythonFun
/Hangman_Game/test_hangman.py
2,330
3.828125
4
from unittest import TestCase import Hangman_Game.Hangman as Hangman class TestHangman(TestCase): def test_update_word_updates_display_word_correctly_for_given_letter(self): word = Hangman.Hangman() word.true_word = "Apple" word.display_word = "_ _ _ _ _" word.update_word("p") self.assertEqual("_ p p _ _", word.display_word) def test_update_word_updates_display_word_to_upper_case_for_starting_letter_in_word(self): word = Hangman.Hangman() word.true_word = "Apple" word.display_word = "_ _ _ _ _" word.update_word("a") self.assertEqual("A _ _ _ _", word.display_word) def test_is_solved_returns_true_when_hangman_is_solved(self): word = Hangman.Hangman() word.true_word = "Apple" word.display_word = "A p p l e" self.assertTrue(word.is_solved()) def test_is_solved_returns_false_when_hangman_is_not_solved(self): word = Hangman.Hangman() word.true_word = "Apple" word.display_word = "A p _ l e" self.assertFalse(word.is_solved()) def test_create_display_string_outputs_correct_string_for_apple(self): word = Hangman.Hangman() word.true_word = "Apple" word.create_display_string() self.assertEqual("_ _ _ _ _", word.display_word) def test_create_display_string_outputs_correct_string_for_orange(self): word = Hangman.Hangman() word.true_word = "Orange" word.create_display_string() self.assertEqual("_ _ _ _ _ _", word.display_word) def test_is_in_word_returns_true_when_letter_in_word(self): word = Hangman.Hangman() word.true_word = "Apple" self.assertTrue(word.is_in_word("l")) self.assertTrue(word.is_in_word("L")) self.assertTrue(word.is_in_word("a")) self.assertTrue(word.is_in_word("A")) def test_is_in_word_returns_false_when_letter_is_not_in_word(self): word = Hangman.Hangman() word.true_word = "Apple" self.assertFalse(word.is_in_word("z")) def test_pick_random_word_can_read_file_with_one_word_in(self): word = Hangman.Hangman() word.pick_random_word("Text.txt") self.assertEqual("Text", word.true_word)
15890b3c25d8da97b18943518357cba494cb0845
sabergjy/Leetcode_Programing
/23.合并K个升序链表.py
3,843
3.921875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: #法一:顺序合并 o(k**2*n) k是链表个数,n为链表长度 python会超时 def mergeTwoListNode(node1, node2): if node1 == None and node2 == None: return None prehead = ListNode() curhead = prehead while node1 and node2: if node1.val <= node2.val: Node_ = ListNode() Node_.val = node1.val curhead.next = Node_ curhead = curhead.next node1 = node1.next else: Node_ = ListNode() Node_.val = node2.val curhead.next = Node_ curhead = curhead.next node2 = node2.next if node1: while node1: Node_ = ListNode() Node_.val = node1.val curhead.next = Node_ curhead = curhead.next node1 = node1.next if node2: while node2: Node_ = ListNode() Node_.val = node2.val curhead.next = Node_ curhead = curhead.next node2 = node2.next return prehead.next if len(lists) == 0: return None if len(lists) == 1: return lists[0] n = len(lists) curListNode = lists[0] lists = lists[1:] for i in range(n-1): curListNode = mergeTwoListNode(curListNode,lists[0]) lists = lists[1:] return curListNode # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: def mergeTwoListNode(node1, node2): if node1 == None and node2 == None: return None prehead = ListNode() curhead = prehead while node1 and node2: if node1.val <= node2.val: Node_ = ListNode() Node_.val = node1.val curhead.next = Node_ curhead = curhead.next node1 = node1.next else: Node_ = ListNode() Node_.val = node2.val curhead.next = Node_ curhead = curhead.next node2 = node2.next if node1: while node1: Node_ = ListNode() Node_.val = node1.val curhead.next = Node_ curhead = curhead.next node1 = node1.next if node2: while node2: Node_ = ListNode() Node_.val = node2.val curhead.next = Node_ curhead = curhead.next node2 = node2.next return prehead.next if len(lists) == 0: return None if len(lists) == 1: return lists[0] #法二:归并合并 o(k*n*logk) l = 0 r = len(lists)-1 def margeListNodeList(l,r): if l == r: return lists[l] mid = (l + r)//2 #取右边 return mergeTwoListNode(margeListNodeList(l,mid),margeListNodeList(mid+1,r)) return margeListNodeList(0,len(lists)-1)
029c5a48acfb93b3b509e58c53459aebc1e3b483
sabergjy/Leetcode_Programing
/25.K 个一组翻转链表.py
1,480
3.78125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: #1.每k个一组组,一循环(执行反转函数) #反转好后头尾接入链表 def reverseKListNode(head,tail): pre = tail.next cur = head while pre != tail: #pre == tail时,链表已经翻转并接好了 nex = cur.next cur.next = pre pre = cur cur = nex return tail, head if k == 1: return head dummyhead = ListNode() dummyhead.next = head hair = dummyhead pre = hair while head: ifHaveNode = pre for i in range(k): ifHaveNode = ifHaveNode.next if ifHaveNode == None: return hair.next #满足有k个节点 tail = ifHaveNode #获取尾结点 #翻转 nex = ifHaveNode.next head, tail= reverseKListNode(head,tail) #拼接链表 pre.next = head #tail.next = nex 这句可以不需要,因为在reverseKListNode函数中已经执行了尾节点的连接 #新的pre和head pre = tail head = nex return hair.next
4fba1f30386a3cd8e90ec4c9082b5133402e7169
poudyalanil/hpc-coursework
/password_cracking/mr.py
1,218
3.90625
4
#!/usr/bin/python3.6 ########################################################################## # # This program is used to run other programs a number of times. The name # of the program to run is the argumnet to this program. Assuming that # this file is named mr.py you need to make sure that it is executable # with: # # chmod a+x mr.py # # You can use it to run a.out 10 times: # # ./mr.py ./a.out # # If you want it to run a different number of times, just change the loop. # This program would benefit from checking that the correct number of # command line arguments have been passed in and a a second argument for # defining the number of times to run. The alterations are left as an # exercise. # # Hints: # - A second argument would be stored in argv[2] # - The number of arguments can be found using len(argv) # # Note: # - The pythoon interpeter to be used is specified in the first line of # the program. If this is different on your system then simply # correct it. # # Dr Kevan Buckley, University of Wolverhampton, 2018 # ########################################################################## import sys from subprocess import call for i in range(0, 10): call(sys.argv[1])
3a4283d222014ac24604cbf34811920b4e9b7834
ElizabethBeck/Class-Labs
/BeckLab02P3.py
412
3.78125
4
T = 1.08 # tax for each day F = 5.00 # one time fee R = 100 # room rate d = int(input("Enter the number of days stayed at the hotel ")) c = 0 # initialize cost variable if (d > 0): # days > 0 # calculations here to compute the solution c = T*(R*d) + F print(" the cost for ", d, " days is ", c ) else: # here m is <= 300 # s <= 0 print(" Invalid entry for days ", d )
2b5033eb83c77c3a40579e70701a7059826e0706
amresh1495/Udemy-course-follow-up-code
/UDEMY_COURSE.PY
4,103
4.59375
5
# Python code follow up on udemy course - The four pillars of object oriented programming in python # check if an employee has achieved his weekly target - class Employee: """attributes like name, designation etc are included below to help understand more about the class""" name = 'Amresh' designation = 'Salesman' salesMadeThisWeek = 6 def salesAchieved(self): if self.salesMadeThisWeek >= 5: print ("Target has been achieved") else: print ("Target has not been achieved") # creating ojbect for Employee class EmployeeOjb = Employee() # accesssing the class attribute using the class object that we created print (EmployeeOjb.name) # accessing the class method using the class object print (EmployeeOjb.salesAchieved()) # new class telling more about attributes - they must be same for all objects for access class employee2: numberOfWorkingHours = 40 employee2obj = employee2() employee2obj2 = employee2() # created two objects for the same class and accessed the class attribute and printed it below # the value of class attribute remains the same for all objects print (employee2obj.numberOfWorkingHours) print (employee2obj2.numberOfWorkingHours) # we can also update the attribute of class employee2.numberOfWorkingHours = 45 # accessing and printing the updated class attribute using object of that class print (employee2obj.numberOfWorkingHours) # making an instance attribute - these are different for different objects employee2obj.name = 'Amresh Giri' print (employee2obj.name) # print (employee2obj2.name) this will give attribute error because it 'name' can't be accessed by other object # we create different attribute for different oject employee2obj2.name = 'Giri Amresh' print (employee2obj2.name) # we can create instance attribute of a class attribute for a particular object # the interpreter first checks for the instance attribute, then looks for class attribute employee2obj.numberOfWorkingHours = 50 print (employee2obj.numberOfWorkingHours) # -> O/P = 50 because instance attribute changed to 50 so it will be reflected # therefore, we can change the class attribute for a particular oject but that won't change its value in the class, it will # change it in the instance attribute of that object # Self parameter class employee3: def employeeDetails(self): # -> self here is an object for creating class instance 'name' self.name = 'Amresh Giri' print ('Name : ', self.name) age = 22 def printEmployeeDetails(self): print ('Age : ', age) @staticmethod def staticMethodDemo(): print ("Welcome to our organization !") emp3ojb = employee3() # calling the class method unconventionally - by passing object of the class employee3.employeeDetails(emp3ojb) # calling the class methos using more conventional way using just the object emp3ojb.employeeDetails() # calling the printEmployeeDetails method #emp3ojb.printEmployeeDetails() # --> this gives error - age not accessible because no instance has been defined for it hence # it can't be accessed outside the method - it's scope is limited # we can avoid using self if not needed by using @staticmethod - when we don't need to use self emp3ojb.staticMethodDemo() # use of init() method - used for initialising the class attributes which are shared by methods # it is the first method to be invoked in the class class emp4: def __init__(self): self.name = 'AMRESH GIRI' def accessDetail(self): print (self.name) emp4obj = emp4() # calling the method accessDetail and accessing already initialized attribute emp4obj.accessDetail() class library: def __init__(self): self.bookCount = 100 def borrow(self): print ("Do you want to borrow a book ?") x = input() if x == 'yes' or x == 'YES': self.bookCount-=1 #@staticmethod def update(self): print ("The number of books currently in the library are : ", self.bookCount) libObj = library() libObj.borrow() libObj.update()
5ddd963bc1354a0593e0797ef80d1078690484cf
Lay-RosaLauren/Coursera-Python-2
/Week02/maisculas.py
671
3.875
4
# Recebe uma string e retorna todas as letras maiúsculas em ordem de ocorrência def maiusculas(frase): maiusculas = [] for i in range(len(frase)): caracter = frase[i] decASCII = ord(caracter) if decASCII > 64 and decASCII < 91: maiusculas.append(caracter) return "".join(maiusculas) # Testa único caracter em maiúsculo def test_unicoMaiusculo(): assert maiusculas('Programamos em python 2?') == 'P' # Testa vários caracteres em maiúsculo def test_variosMaiusculos(): assert maiusculas('PrOgRaMaMoS em python!') == 'PORMMS' assert maiusculas('Programamos em Python 3.') == 'PP'
eb21641a0bc733a13df560c458d10749d4b72fa4
Lay-RosaLauren/Coursera-Python-2
/Week01/matriz_mult.py
323
3.546875
4
def dimensoes(matriz): return (len(matriz), len(matriz[0])) # Verifica se as matrizes recebidas são multiplicavéis def sao_multiplicaveis(m1, m2): dimensao_m1 = dimensoes(m1) dimensao_m2 = dimensoes(m2) if dimensao_m1[1] == dimensao_m2[0]: return True else: return False
1cc6852def3f885aa8a276a33991329e27cc8db3
Lay-RosaLauren/Coursera-Python-2
/Week06/elefantes1.py
448
3.96875
4
def incomodam(n): if type(n) != int or n <= 0: return '' else: str1 = 'incomodam ' return str1 + incomodam(n - 1) def elefantes(n): if type(n) != int or n <= 0: return '' if n == 1: return "Um elefante incomoda muita gente" else: return elefantes(n - 1) + str(n) + " elefantes " + incomodam(n) + ("muita gente" if n % 2 > 0 else "muito mais") + "\r\n"
a949ddd50bbad777b1b1d054e743330ffa8a5921
TILhub/Data-Cleaning
/NLTK basic cleaning/Keywords.py
2,379
3.625
4
#author Sahil Malik #Time 12:34 AM #Location New Delhi import nltk #for removing conjunctions pronouns and prepositions from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import string from nltk.stem.porter import PorterStemmer #reading input file file1=open('text.txt','r') text=file1.read() file1.close() # split into words and lower case every word tokens = word_tokenize(text) tokens = [w.lower() for w in tokens] #remove punctuations from each word table = str.maketrans('', '', string.punctuation) stripped = [w.translate(table) for w in tokens] #remove remaining tokens that are not alphabetic words = [word for word in stripped if word.isalpha()] #filter stop words stop_words = set(stopwords.words('english')) words = [w for w in words if not w in stop_words] #print(words[:100]) # stemming of words porter = PorterStemmer() stemmed = [porter.stem(word) for word in words] print(stemmed[:100]) """ This criterion advantages sentences that contain keywords. To determine the web page keywords, we suggest to use the tf.idf technique (Term Frequency Inverse Document Frequency times) used in information retrieval to assign weights to the terms (words) of a document. According to the tf.idf technique a word is important if it is relatively common in the web page and relatively rare in a large collection consisting of web pages linked by hypertext links to that web page. We propose to ignore the "empty" words (e.g. conjunctions, pronouns, prepositions, etc.) that figure in a fixed list and calculate the tf.idf for the remaining terms using the following formula: n w tf N i j ij = ×log where wij is the weight of the term Tj in the page Pi ; tfij is the frequency of the term Tj in the page Pi ; N is the number of pages linked by hypertext links to the page Pi ; n is the number of pages where the term Tj occurs at least once. We calculate for each word of the web page its tf.idf and we retain as keywords only those which tf.idf is above the average tf.idf. The retained keywords are then enriched with the keywords that are in the keywords Meta tag (if it is available in the HTML file of the Web page). The score of a sentence s, according to this criterion is the number of keywords contained in the processed sentence: C3(s) = number of keywords of the sentence s. """
56b3c204f607e7fb1c4ff4062df9c733b24ccbc2
ZhiweiPan/week5-6
/prac3-4.py
7,458
3.78125
4
import tkinter import math import tkinter.messagebox class Calculator: def __init__(self): self.root = tkinter.Tk() self.root.minsize(280,450) self.root.maxsize(280,480) self.root.title("Simplified Calculator") self.result = tkinter.StringVar() self.result.set(0) self.lists =[] self.ispressign = False self.layout() self.root.mainloop() def layout(self): result = tkinter.StringVar() result.set(0) show_label = tkinter.Label(self.root, bd = 3, bg = "white" , font = ('宋体',30), anchor = "e", textvariable =self.result) show_label.place(x = 5,y =20 ,width = 270,height = 80) button_mc =tkinter.Button(self.root, text = "MC", command = self.wait) button_mc.place(x=5,y=100,width = 50,height = 50) button_mr = tkinter.Button(self.root, text="MR", command=self.wait) button_mr.place(x=60, y=100, width=50, height=50) button_ms = tkinter.Button(self.root, text="MS", command=self.wait) button_ms.place(x=115, y=100, width=50, height=50) button_mplus = tkinter.Button(self.root, text="M+", command=self.wait) button_mplus.place(x=170, y=100, width=50, height=50) button_mminus = tkinter.Button(self.root, text="M-", command=self.wait) button_mminus.place(x=225, y=100, width=50, height=50) button_del = tkinter.Button(self.root, text="←", command=self.dele_one) button_del.place(x=5, y=155, width=50, height=50) button_ce = tkinter.Button(self.root, text="CE", command=lambda:self.result.set(0) ) button_ce.place(x=5, y=155, width=50, height=50) button_del = tkinter.Button(self.root, text="←", command=self.dele_one) button_del.place(x=60, y=155, width=50, height=50) button_C = tkinter.Button(self.root, text="C", command=self.sweepress) button_C.place(x=115, y=155, width=50, height=50) button_pm = tkinter.Button(self.root, text="±", command=self.pm) button_pm.place(x=170, y=155, width=50, height=50) button_sqr = tkinter.Button(self.root, text="√", command=self.sqr) button_sqr.place(x=225, y=155, width=50, height=50) button_del = tkinter.Button(self.root, text="←", command=self.dele_one) button_del.place(x=5, y=155, width=50, height=50) button_seven = tkinter.Button(self.root, text="7", command=lambda: self.pressnum("7")) button_seven.place(x=5, y=210, width=50, height=50) button_eight = tkinter.Button(self.root, text="8", command=lambda: self.pressnum("8")) button_eight.place(x=60, y=210, width=50, height=50) button_nine = tkinter.Button(self.root, text="9", command=lambda: self.pressnum("9")) button_nine.place(x=115, y=210, width=50, height=50) button_division = tkinter.Button(self.root, text="÷", command=lambda :self.presscalculate("/")) button_division.place(x=170, y=210, width=50, height=50) button_remainder = tkinter.Button(self.root, text="//", command=lambda :self.presscalculate("//")) button_remainder.place(x=225, y=210, width=50, height=50) button_four = tkinter.Button(self.root, text="4", command=lambda: self.pressnum("4")) button_four.place(x=5, y=265, width=50, height=50) button_five = tkinter.Button(self.root, text="5", command=lambda: self.pressnum("5")) button_five.place(x=60, y=265, width=50, height=50) button_six = tkinter.Button(self.root, text="6", command=lambda: self.pressnum("6")) button_six.place(x=115, y=265, width=50, height=50) button_mutip = tkinter.Button(self.root, text="×", command=lambda :self.presscalculate("×")) button_mutip.place(x = 170, y=265, width=50, height=50) button_recip = tkinter.Button(self.root, text="1/x", command=lambda: self.ds) button_recip.place(x=225, y=265, width=50, height=50) button_one = tkinter.Button(self.root, text="1", command=lambda: self.pressnum("1")) button_one.place(x=5, y=320, width=50, height=50) button_two = tkinter.Button(self.root, text="2", command=lambda: self.pressnum("2")) button_two.place(x=60, y=320, width=50, height=50) button_three = tkinter.Button(self.root, text="3", command=lambda: self.pressnum("3")) button_three.place(x=115, y=320, width=50, height=50) button_minus = tkinter.Button(self.root, text="-", command=lambda: self.presscalculate("-")) button_minus.place(x=170, y=320, width=50, height=50) button_eq = tkinter.Button(self.root, text="=", command=lambda: self.pressequal()) button_eq.place(x=225, y=320, width=50, height=105) button_zero = tkinter.Button(self.root, text="0", command=lambda :self.pressnum("0")) button_zero.place(x=5, y=375, width=105, height=50) button_point= tkinter.Button(self.root, text=".", command=lambda: self.pressnum(".")) button_point.place(x=115, y=375, width=50, height=50) button_plus = tkinter.Button(self.root, text="+", command=lambda: self.presscalculate()) button_plus.place(x=170, y=375, width=50, height=50) def pressnum(self,num): if self.ispressign == False: pass else: self.result.set(0) self.ispressign = False if num == ".": num = "0." oldnum = self.result.get() if oldnum == "0": self.result.set(num) else: newnum = oldnum + num self.result.set(newnum) def presscalculate(self,sign): num = self.result.get() self.lists.append(num) self.lists.append(sign) self.ispressign = True def pressequal(self): curnum = self.result.get() self.lists.append(curnum) calculatestr = ''. join(self.lists) endnum = eval(calculatestr) self.result.set(str(endnum)[:10]) if self.lists != 0: self.ispressign = True self.lists.clear() def wait(self): tkinter.messagebox.showinfo('','Sorry, This function is still tried to implement. Please wait!') def dele_one(self): if self.result.get() == '' or self.result.get() == "0": self.result.set('0') return else : num = len(self.result.get()) if num >1 : strnum = self.result.get() strnum = strnum[0:num-1] self.result.set(strnum) else: self.result.set('0') def pm(self): strnum = self.result.get() if strnum[0] == "-": self.result.set(strnum[1:]) elif strnum[0] != '-' and strnum != "0": self.result.set('-' + strnum) def ds(self): dsnum = 1/int(self.result.get()) self.result.set(str(dsnum)[:10]) if self.lists != 0: self.ispressign = True self.lists.clear() def sweepress(self): self.lists.clear( ) self.result.set(0) def sqr(self): strnum = float(self.result.get()) endnum = math.sqrt(strnum) if str(endnum)[-1] == "0": self.result.set(str(endnum)[:-2]) else: self.result.set(str(endnum)[:10]) if self.lists != 0: self.ispressign = True self.lists.clear() mycalculator = Calculator()
9d2e0456cc294c606ac2c33bdafa79de7ad19e26
Likitha-dotcom/Python_Lab
/modules/operator_overloading.py
870
3.796875
4
#overload operators and function using modules class Oper: def __init__(self): self.alist=[] def get(self): n=int(input("Enter the list size:")) for i in range(0,n): ele=int(input("Enter the elements:")) self.alist.append(ele) #print(self.alist) def __add__(self,other): new_list=[] for i in range(0,len(self.alist)): new_list.append(self.alist[i]+other.alist[i]) print(new_list) def __sub__(self,other): new_list=[] for i in range(0,len(self.alist)): new_list.append(self.alist[i]-other.alist[i]) print(new_list) def __mul__(self,other): new_list=[] for i in range(0,len(self.alist)): new_list.append(self.alist[i]*other.alist[i]) print(new_list) def __floordiv__(self,other): new_list=[] for i in range(0,len(self.alist)): new_list.append(self.alist[i]//other.alist[i]) print(new_list) #ov1=Oper() #ov2=Oper()
d25230bedac976f12660889de3f7f67481c73472
ShirkeJR/PythonLearn
/Zajecia25.10.2017/zad1.py
1,116
3.5625
4
import math class LiczbaZespolona: def __init__(self, a, b): self.a = a self.b = b self.modul = self.__funModul() def __str__(self): return "%i + %ii" % (self.a, self.b) def __add__(self, other): return LiczbaZespolona(self.a + other.a, self.b + other.b) def __sub__(self, other): return LiczbaZespolona(self.a - other.a, self.b - other.b) def __mul__(self, other): return LiczbaZespolona(self.a * other.a - self.b * other.b, self.a * other.b + self.b * other.a) def __div__(self, other): return LiczbaZespolona((self.a * other.a + self.b * other.b)/(math.pow(other.a,2) + math.pow(other.b,2)), (self.b * other.a - self.a * other.b)/(math.pow(other.a,2) + math.pow(other.b,2))) def __funModul(self): self.modul = math.sqrt(math.pow(self.a, 2) + math.pow(self.b, 2)) def __cmp__(self, other): return self.modul > other.modul a = LiczbaZespolona(5, 1) b = LiczbaZespolona(5, 1) b = a print(b) print(a+b) print(a-b) print(a*b) print(a/b) if(a == b): print("Sa rowne") else: print("Nie sa rowne")
d3bf0386cc51e9709cc35a2225eba8057487eefe
ShirkeJR/PythonLearn
/Zajecia22.11.2017/zad1.py
458
3.53125
4
import math def pobierzLiczbe(liczba): try: pierw = math.sqrt(liczba) except (TypeError, ValueError) as ex: print "Zle dane: " + str(ex) else: return pierw finally: print "Koniec" print pobierzLiczbe(2) print pobierzLiczbe(-2) print pobierzLiczbe("Tak") try: liczba = input("Podaj liczbe do pierw: ") except (NameError, SyntaxError): print "Zly format danych" else: print pobierzLiczbe(liczba)
4a495068d36aa5efa2386abec4581c5f791d57d1
ShirkeJR/PythonLearn
/DiceGame/Rule.py
1,671
3.609375
4
from collections import Counter class Rule(object): @staticmethod def calculate_points(rule, dices): most_common_result = Counter(dices).most_common() if rule == "a": return sum(dice.result == 1 for dice in dices) elif rule == "b": return sum(dice.result == 2 for dice in dices) * 2 elif rule == "c": return sum(dice.result == 3 for dice in dices) * 3 elif rule == "d": return sum(dice.result == 4 for dice in dices) * 4 elif rule == "e": return sum(dice.result == 5 for dice in dices) * 5 elif rule == "f": return sum(dice.result == 6 for dice in dices) * 6 elif rule == "g": if most_common_result[0][1] == 3: return most_common_result[0][0].result * most_common_result[0][1] elif rule == "h": if most_common_result[0][1] == 4: return most_common_result[0][0].result * most_common_result[0][1] elif rule == "i": if len(most_common_result) == 2: return 25 elif rule == "j": a = [1, 2, 3, 4] b = [2, 3, 4, 5] c = [3, 4, 5, 6] if a or b or c in dices: return 30 elif rule == "k": a = [1, 2, 3, 4, 5] b = [2, 3, 4, 5, 6] if a or b in dices: return 40 elif rule == "l": if most_common_result[0][1] == 5: return most_common_result[0][0] * most_common_result[0][1] elif rule == "m": return sum(dice.result for dice in dices) return 0
cb229252f297caac2a1dcdb71e42c1fec72bbd2b
liamdebell/liamdebell.github.io
/py/task3_c.py
179
3.921875
4
force = [] numberlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] num = int(5) for i in numberlist: if i < num: force.append(i) sumf = sum(force) print(force, "or the sum: ", sumf)
4f1671979fb8a51eefc77dbad2241fc96d6c01f8
haohaowasky/Sliding-Window-Average
/Version1.py
587
3.6875
4
class MovingAverage(object): def __init__(self, size): # Initialize your data structure here. self.size = size self.sum = 0.0 self.array = [] self.counter = 0 # @param {int} val an teger def next(self, val): # Write your code here self.counter+= 1 self.sum+= val self.array.append(self.sum) if self.counter<= self.size: return self.sum/self.counter else: return (self.sum- self.array[self.counter- self.size- 1])/self.size
72ff2bdee4d6faa9f8e7327632f427c1d932cb05
Behzadkha/Python
/src/ReadAllocationData.py
2,806
3.671875
4
## @file ReadAllocationData.py # @author Behzad Khamneli # @brief This code reads student information and returns the necessary files for allocation of students. # @date 1/18/2019 ## @brief This function returns a list of dictionaries of student information. # @details ReadStdnts accepts a string corresponding to a file name. If there is something wrong with the file name, it returns an error message. # @param s Is a filename with the following format : macid firstname lastname gender gpa choice choice choice for every student (every line for a single students). # @return A dictionary with format : {'macid': string, 'fname': string, 'lname': string, 'gender': string, 'gpa': float, 'choices': [string, string, string]}. def readStdnts(s): try: contents = [] choices = [] stdnList = [] dicty = {} file = open(s, "r") for line in file.readlines(): contents = (line.split()) dicty["macid"] = str(contents[0]) dicty["fname"] = str(contents[1]) dicty["lname"] = str(contents[2]) dicty["gender"] = str(contents[3]) dicty["gpa"] = float(contents[4]) choices.append(str(contents[5])) choices.append(str(contents[6])) choices.append(str(contents[7])) dicty["choices"] = choices choices = [] stdnList.append(dicty) dicty = {} file.close() return stdnList except: return "File Error" ## @brief This function filters students with freechoice. # @param s Is a filename with the following format: macid FreeChoice if a student has a free choice and format : macid no for student without a freechoice (on every line). # @details If there is an error in the file name, function readFreeChoice returns an error. # @return A list of string, where each entry in the list corresponds to the macid of a student with free choice. def readFreeChoice(s): try: contents = [] FreeChoiceStdn = [] numberofStdn = 0 file = open(s, "r") for line in file.readlines(): contents.append(line.split()) numberofStdn += 1 for i in range (numberofStdn): if 'FreeChoice' in contents[i]: FreeChoiceStdn.extend(contents[i]) FreeChoiceStdn.remove("FreeChoice") file.close() return FreeChoiceStdn except: return "File Error" ## @brief Takes a string and returns a dictionary. # @details This function separates department name and its capacity. department name goes to dept(list) and its capacity goes to capacity(list). # @param s Is a filename with the following format : departmentName capacity on each line. # @return A dictionary with the following format : {'dept': integer}. def readDeptCapacity(s): try: dept = [] capacity = [] dicty = {} file = open(s, "r") for line in file.readlines(): dept, capacity = line.split() dicty[dept] = int(capacity) file.close() return dicty except: return "File Error"
171326d5db817cc063ba21f5c68d78b15da34b42
ItaiHenn/BIU-Engineering-2021
/Ex_4_Q_4_by_Dudu_Gvili.py
1,291
3.953125
4
#A restaurant networks want to open branches along a highway #there are 'n' available places given in list m[] #at each location you can open 1 restaurant and the profit will be according to list p[] in same index of m[] #the distance between 2 branches has to be atleast 'k' #write an algorithm that find the maximum profit locations arangement/ #1. calculating list c[] of closest place to open a restaraunt if i opened one at m[i] #2. making a list of T - total profit, R - opened restaurants #3. comparing 2 options - not opening a branch at location i and then T[i] will be the same as T[i-1] # or opening a branch at location i and taking that branch profit (p[i]) + the total profit of the branches before it in distance of atleast k (T[c[i]]) def maxProfitLocations(m, p, c): T = [0] R = [0]*len(m)ches for i in range(1,n): open_i = T[i-1] no_open_i = p[i] + T[c[i]] if no_open_i > open_i: T[i] = no_open_i else: T[i] = open_i R[i] = 1 return T, R def findCi(m, k): c = [0] for i in range (1, len(m)): j = c[i-1] while (m[j+1] <= m[i]-k): j += 1 c.append(j) return c def driverCode(m, p, k): maxProfitLocations(m, p, findCi(m, k))
2522084a92aab51849700787b5014b1da2f5aa09
NorahJC/RegressionAnalyses
/SimpLinReg.py
3,417
3.9375
4
##Norah Jean-Charles ##2/4/2019 ##Simple Linear Regression ##Dr.Aledhari ##CS4267-Machine Learning ##Section 1 ##Spring 2019 import numpy as np import pandas as pd import matplotlib.pyplot as plt # Import dataset dataset = pd.read_csv('Salaries-Simple_Linear.csv') print(dataset) # Gives (# of rows, # of col) ##print(dataset.shape) # Divide data set into x(years) and y(salaries) x = dataset.iloc[:, :-1].values ##x = dataset['Years_of_Expertise'].values##does not transpose values ##print(x) y = dataset.iloc[:, 1].values ##y = dataset['Salary'].values##does not do transpose ##print(y) # Get mean mean_x = np.mean(x) mean_y = np.mean(y) print('Means: x = %.3f, y = %.3f' % (mean_x, mean_y)) ###or ## ###calc the mean value of a list of #s ##def mean(values): ## return sum(values) / float(len(values)) ## ###calc variance of a list of numbers ##def variance(values, mean): ## return sum([(x-mean)**2 for x in values]) ###get mean and variance ##mean_x, mean_y = mean(x), mean(y) ##var_x, var_y = variance(x, mean_x), variance(y, mean_y) ##print('x stats: mean=%.3f variance=%.3f' % (mean_x, var_x)) ##print('y stats: mean=%.3f variance=%.3f' % (mean_y, var_y)) ## ## ###calc covariance between x and y ##def covariance(x, mean_x, y, mean_y): ## covar = 0.0 ## for i in range(len(x)): ## covar += (x[i] - mean_x) * (y[i] - mean_y) ## return covar ## ###calc the mean and variance ##covar = covariance (x, mean_x, y, mean_y) ##print('Corvariance: %.3f' % (covar)) ## ###calc coefficients ##def coefficients(dataset): ## x_mean, y_mean = mean(x), mean(y) ## b1 = covariance(x, x_mean, y, y_mean) / variance(x, x_mean) ## b0 = y_mean - b1 * x_mean ## return [b0, b1] ## ### calc the coefficients ##b0, b1 = coefficients(dataset) ##print('Coefficients: B0=%.3f, B1=%.3f' % (b0, b1)) # Total number of values m = len(x) # Use regression model to calculate b1 and b2 numer = 0 denom = 0 for i in range(m): numer += (x[i] - mean_x) * (y[i] - mean_y) denom += (x[i] - mean_x) ** 2 b1 = numer / denom b0 = mean_y - (b1 * mean_x) # Print coefficients print('Coefficents: b0 = %.3f, b1 = %.3f' % (b0, b1)) # Print cost function/ linear regression model a = 'Salary' b = 'Years_of_Expertise' cfunct = '%s = %.3f + %.3f * %s' % (a, b0, b1, b) # Print cost function equation print('Based on the linear regression model, y = B0 + B1 * x, the cost function is \n\t %s' % (cfunct)) ## ### Plot values and regression line ##max_x = np.max(x) + 100 ##min_x = np.min(x) - 100 ## ### Calculating line values x and y ##x1 = np.linspace(min_x, max_x, 1000) ##y1 = b0 + b1 * x1 ### Ploting Line ##plt.plot(x1, y1, color='#58b970', label='Regression Line') ### Ploting Scatter Points ##plt.scatter(x, y, color='#ef5423', label='Scatter Plot') ## ##plt.xlabel('Years of Expertise') ##plt.ylabel('Salary') ##plt.legend() ##plt.show() from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 1/3, random_state = 0) from sklearn.linear_model import LinearRegression simplelinearRegression = LinearRegression() simplelinearRegression.fit(x_train, y_train) y_predict = simplelinearRegression.predict(x_test) plt.scatter(x_train, y_train, color = 'red') plt.plot(x_train, simplelinearRegression.predict(x_train)) plt.title('Predicting Salary Based on Years of Expertise') plt.xlabel('Years of Expertise') plt.ylabel('Salary') plt.show()