blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ab33eed9ded9a48108f812dcda7ca6c7b648f78d
mazzuccoda/condicionales_python
/ejemplos_clase/ejemplo_2.py
1,606
4.375
4
# Condicionales [Python] # Ejemplos de clase # Autor: Inove Coding School # Version: 2.0 # Ejemplos con if anidados (elif) y compuestos # Uso de if anidados (elif) # Verificar en que rango está z # mayor o igual 50 # mayor o igual 30 # mayor o igual 10 # menor a 10 z = 25 if z >= 50: print("z es mayor o igual a 50") elif z >= 30: print("z es mayor o igual a 30") elif z >= 10: print("z es mayor o igual a 10") elif z < 10: print("z es menor 10") else: print("no se encuentro ningún rango válido") # Condicionales compuestos numero_1 = 10 numero_2 = 30 numero_3 = -20 # Calcular el producto entre dos números enteros que ambos sean positivos if numero_1 > 0 and numero_2 > 0: producto = numero_1 * numero_2 print('El producto entre {} y {} es {}'.format(numero_1, numero_2, producto)) # Calcular el producto entre dos números enteros si al menos uno de los dos es positivo if numero_1 > 0 or numero_2 > 0: producto = numero_1 * numero_2 print('El producto entre {} y {} es {}'.format(numero_1, numero_2, producto)) # Calcular la suma de dos números si almenos uno de ellos # es mayor o igual a cero if numero_1 >= 0 or numero_3 >= 0: suma = numero_1 + numero_3 print('La suma entre {} y {} es {}'.format(numero_1, numero_3, suma)) # Calcular el producto entre dos números enteros que ambos sean positivos # y ambos menores a 100 if (numero_1 > 0 and numero_2 > 0) and (numero_1 < 100 and numero_2 < 100): producto = numero_1 * numero_2 print('El producto entre {} y {} es {}'.format(numero_1, numero_2, producto)) print("terminamos!")
69443133329be49a4616a1d6ad32102f20261177
mazzuccoda/condicionales_python
/ejemplos_clase/ejemplo_4.py
443
3.78125
4
# Condicionales [Python] # Ejemplos de clase # Autor: Inove Coding School # Version: 2.0 # Ejemplos varialbles de texto y condicionales compuestos texto_1 = 'a' texto_2 = 'b' # Condicionales compuestos # Si texto_1 es mayor a texto_2 e igual a "hola" o # texto_1 tiene menos de 4 letras, entonces imprimir "Correcto!" if (((texto_1 > texto_2) and texto_1 == 'hola') or (len(texto_1) < 4)): print('Correcto!') print("terminamos!")
ddea117c8cf14be360814c08d998e01c41e7ba6f
brandonharris177/edabit-challanges
/coding.py
835
3.703125
4
def findTarget(givenList, target): check = set() answers = [] for number in givenList: difference = target-number if difference in check and number != difference: answers.append([number, difference]) else: check.add(number) print(answers) return answers # findTarget([5, 2, 3, 4, 1], 6) #if 2 strings are isomorphic (mapping between them that will presever order) #eag aed def isIsomorphic(string1, string2): hashTable = {} for index in range(len(string1)): if string1[index] not in hashTable: hashTable[string1[index]] = string2[index] else: if hashTable[string1[index]] != string2[index]: return False return True print(isIsomorphic("paper", "title"))
25643f1d6de74fd7456a0bbb9d2413a31ae7fe08
venkatesha-ch/CN-lab
/lab-8/crc.py
1,390
3.5
4
import hashlib def xor(a, b): result = [] for i in range(1, len(b)): if a[i] == b[i]: result.append('0') else: result.append('1') return ''.join(result) def mod2div(dividend, divisor): pick = len(divisor) tmp = dividend[0: pick] while pick < len(dividend): if tmp[0] == '1': tmp = xor(divisor, tmp) + dividend[pick] else: tmp = xor('0' * pick, tmp) + dividend[pick] pick += 1 if tmp[0] == '1': tmp = xor(divisor, tmp) else: tmp = xor('0' * pick, tmp) checkword = tmp return checkword def encodeData(data, key): l_key = len(key) appended_data = data + '0' * (l_key - 1) remainder = mod2div(appended_data, key) codeword = data + remainder return codeword def decodeData(code, key): remainder = mod2div(code, key) return remainder data=input("Enter Data: ") print("dataword:"+str(data)) key = "10001000000100001" print("generating polynomial:"+key) codeword = encodeData(data, key) print("Checksum: ",codeword) print("Transmitted Codeword:"+str(codeword)) code = input("enter transmitted codeword:") recieved_data = int(decodeData(code, key)) if recieved_data == 0: print("NO ERROR") else: print("ERROR") print(recieved_data)
57fb4b6b780d04485c0829299e2ecc336773dc3f
rohit04saluja/micro-codes
/python/Data Structures/Sort/InsertionSort.py
157
3.71875
4
def sortInsertion(a=[]) for i in range(1,len(a)): temp = a[i] j = i-1 while j>=0 and a[j]>temp: a[j+1] = a[j] j = j-1 a[j+1] = temp return a
2ce7405a05b17529f672255ccc275a28000c638f
a01229599/Tarea-02
/auto.py
413
3.84375
4
#encoding: UTF-8 # Autor: Dora Gabriela Lizarraga Gonzalez, A01229599 # Descripcion: Se calculara la distancia o tiempo que tarda un auto de acuerdo a la velocidad introducida. # A partir de aquí escribe tu programa velocidad = int(input('Velocidad del auto en km/h: ')) distancia6 = (velocidad*6) distancia10 = (velocidad*10) tiempo500 = (500/velocidad) print (distancia6 , 'km') print (distancia10 , 'km') print (tiempo500 , 'hrs.')
4e803bff30fe637c684e0624314cf600f3009c2d
elissindricau/spanzuratoarea
/joc.py
3,085
3.875
4
""" sa apara un cuvant ascuns si fiecare litera sa apara codata printr-o linie cand utilizatorul introduce o litera daca litera se afla in cuvant, reafisam cuvantul cu litera respectiva de oricate ori apare cuvantu daca s-a ghicit si ultima litera, se afiseaza un mesaj de final daca nu se gaseste litera, se afiseaza cate sanse mai are jucatorul daca nu mai are sanse, se afiseaza un mesaj de pierdere optional: afisam omuletul """ import random lista_cuvinte = ['caine', 'girafa', 'lalea', 'lup', 'pisica', 'elefant', 'castor', 'maimuta', 'delfin', "cal", "capra"] nr_vieti = 6 spanzuratoare = [ " ________", " | |", " |", " |", " |", " ___|___" ] lista_linii = [ (0, 0, "0"), (2, 5, "O"), (3, 4, "/"), (3, 5, "|"), (3, 6, "\\"), (4, 4, "/"), (4, 6, "\\") ] def adauga_membru(lista_linii, sansa, spanzuratoare): membru = nr_vieti - sansa if membru == 0: return spanzuratoare else: linia, randul, valoarea = lista_linii[membru] linia_noua = schimba_chr(randul, valoarea, spanzuratoare[linia]) spanzuratoare[linia] = linia_noua return spanzuratoare def afisare_spanzuratoare(spanzuratoare): for linie in spanzuratoare: print(linie) def schimba_chr(index, chr, cuvant): cuvant = cuvant[:index] + chr + cuvant[index+1:] return cuvant def afisare_cuvant(cuv): sir = "" for i in range(len(cuv)): sir = sir + cuv[i] + " " print(sir) def joc(): print("Bine ai venit in jocul Spanzuratoarea!") print("by Eliss Indricau") raspuns = "da" while raspuns == "da": raspuns = "nu" cuvant = random.choice(lista_cuvinte) cuvant_linii = genereaza_linii(cuvant) spanzuratoarea(cuvant, cuvant_linii) raspuns = input("Vrei sa mai joci? (da/nu): ") def spanzuratoarea(cuvant, sir): jocul_continua = True sanse = nr_vieti spanzuratoare_noua = spanzuratoare while jocul_continua: print("Mai ai {} sanse".format(sanse)) afisare_spanzuratoare(spanzuratoare_noua) afisare_cuvant(sir) litera = input("Scrie o litera: ") litera_gasita = False for i in range(len(cuvant)): if cuvant[i] == litera: litera_gasita = True sir = schimba_chr(i, litera, sir) #print(sir) if not litera_gasita: sanse -= 1 spanzuratoare_noua = adauga_membru(lista_linii, sanse, spanzuratoare_noua) if sanse == 0: jocul_continua = False afisare_spanzuratoare(spanzuratoare_noua) print("Ai pierdut!") print("Cuvantul tau a fost: ") afisare_cuvant(cuvant) if sir == cuvant: jocul_continua = False print("Ai castigat!") print("Cuvantul tau este: ") afisare_cuvant(cuvant) def genereaza_linii(cuvant): sir = "" for i in range(len(cuvant)): sir = sir + "_" return sir joc()
64aee295be7af99988d96dfab4e7e76d0a6d8148
nguyenduongkhai/sandbox
/pract1/loops.py
559
3.890625
4
def main(): #Example for i in range(1, 21, 2): print(i, end=' ') print() #a for i in range(0, 110, 10): print(i, end=' ') print() #b for i in range(20, 0, -1): print(i, end=' ') print() #c stars =int(input("How many starts you want me to print:")) for i in range(stars ): print('*',end='') print('\n\n') #d count_stars=(int)(input("Input here:")) for i in range(count_stars+1): for j in range (i): print('*',end='') print() main()
5339f59f718a304990c3d25c3a9603ca244b8974
nguyenduongkhai/sandbox
/prac2/word.generator.py
377
4.125
4
import random def main(): VOWELS = "aeiou" CONSONANTS = "bcdfghjklmnpqrstvwxyz" name = input("Please enter a sequence of Consonants(c) and Vowels(v)") word_format = name word = "" for kind in word_format: if kind == "c": word += random.choice(CONSONANTS) else: word += random.choice(VOWELS) print(word) main()
d407702e562704e0137d5901604487aa25ddece9
emiliotebar/Ejercicios-python
/acumulado.py
406
3.8125
4
""">>> acumulado([1, 5, 7]) [1, 6, 13] >>> acumulado([1, 0, 1, 0, 1]) [1, 1, 2, 2, 3] >>> acumulado([]) [] """ l = [1, 5, 7] def acumulado(lista): lista_acumulada = [] for i in range(len(lista)): if (i == 0): lista_acumulada.append(lista[i]) else: lista_acumulada.append(lista_acumulada[i-1] + lista[i]) return lista_acumulada print(acumulado(l))
805ff6d1b5d8be80ab2dbd7bf617f641fe793317
yangrchen/team-jordan-leetcodes
/medium/1423-max-points-from-cards.py
972
3.859375
4
# Time: O(n), Space: O(1) # Relevant Concepts: Sliding Window Technique # set up a first sum that is the sum of first k elements of cardPoints and make this the first max # use the sliding window technique to avoid a double for loop: # in each iteration remove the deepest element at the front # add the deepest element from the end # check if your new current sum is greater than max # Thoughts -> you kinda have to imagine the list is a loop since you are sliding across a joint front and end class Solution(object): def maxScore(self, cardPoints, k): """ :type cardPoints: List[int] :type k: int :rtype: int """ current_sum = sum(cardPoints[:k]) max_sum = current_sum for i in range(1, k + 1): current_sum -= cardPoints[k - i] current_sum += cardPoints[len(cardPoints) - i] if current_sum > max_sum: max_sum = current_sum return max_sum
4756cfd8904e84fbc1c5d886b5b3c737f2e2efeb
poly451/Evolutionary-Algorithms
/base_libs.py
2,572
3.71875
4
""" =================================== class Tile =================================== """ class Tile: def __init__(self, x, y, contents): # print("in tile, contents are of type: {}".format(type(contents))) if not isinstance(contents, str): print("contents ({}) are NOT of type string. They are of type: {}".format(contents), type(contents)) pygame.quit() sys.exit("Error in class Tile. Contents were not of type str.") self._x = x self._y = y self._contents = contents self.neighbors = [] @property def contents(self): temp = [] temp.append(self._x) temp.append(self._y) temp.append(self._contents) return temp @contents.setter def contents(self, value): # I've changed my mind, there is no reason x or y should ever be changed. # read/accessed, sure, but not changed. # if not isinstance(value, list): # print("value ({}) is NOT of type list. It is of type: {}".format(value), type(value)) # pygame.quit() # sys.exit("Error in class Tile in def contents (property setter). Contents were not of type list.") # if not isinstance(value[0], int): # raise ValueError("Contents ({}) are not of type int. They are of type ({}).".format(value[0], type(value[0]))) # if not isinstance(value[1], int): # raise ValueError("Contents ({}) are not of type int. They are of type ({}).".format(value[1], type(value[1]))) if not isinstance(value, str): raise ValueError("Contents ({}) are not of type str. They are of type ({}).".format(value, type(value))) # self._x = value[0] # self._y = value[1] self._contents = value def drop_neighbors(self): self.neighbors = [] def has_neighbors(self): if len(self.neighbors) > 0: return True return False # def get_nothing_tile(self): # new_tile = Tile(-1, -1, "nothing") # new_tile.neighbors = [] # return new_tile def debug_print(self): print_string = "{}-{}-{}-[{}] || ".format(self._x, self._y, self._contents, len(self.neighbors)) # print_string = "{}-{}-{} || ".format(self._x, self._y, self._contents) print(print_string) def return_string(self): # print("{}-{}-{}".format(self._x, self._y, self._contents)) return "{}-{}-{}-[{}] || ".format(self._x, self._y, self._contents, len(self.neighbors))
9d91d5e289556391b01c3d294144e83aad953472
jackR288817/pg_jr
/Personality_JF.py
837
3.921875
4
import time name = "Josh" state = "Florida" city = "new york city" game = "steep" book = "Tina Fey" print(name + " likes to visit " + state + " and " + city) print("He also likes pwning on " + game + " or reading " + book) print("What's your favorite subject?") subject = input () if subject == "math": print("That's awsome!") else: print(subject + " is a good course too.") print("What's your favorite sport?") sport = input() if sport == "Baseball" or sport == "Basketball": print("I love " + sport + " too!") else: print(sport + " is pretty fun.") print("Favorite movie?") movie = input() if movie == "42": print("What is that?") elif movie == "Blind Side": print("Woah!") else: print("I've never seen " + movie) time.sleep(100)
3daad6e7501f7f64897b565bc83fb587c7249fea
onifs10/PythonCPE401
/multiplication.py
2,496
3.703125
4
import matplotlib.pyplot as plt def multiplication(input_a_param: str, input_b_param: str): input_a_param = binary_4bit_num(input_a_param) input_b_param = binary_4bit_num(input_b_param) a = [0] * 8 b = [0] * 8 result = [0] * 8 a[4:8] = [int(i) for i in input_a_param] copy_a = [i for i in a] b[4:8] = [int(i) for i in input_b_param] copy_b = [i for i in b] print('Multiplicand = ', a) print('\n') print('Multiplier = ', b) print('\n') print('*********************') if b[7] == 1: # print(f"{b[7]} the value of LSB b[0] , initializes the result as the value of A") # debug result = [i for i in a] for i in range(6, 3, -1): # 6 , 5 , 4 if b[i] == 1: # if the bit at that point is one shift and add # print(f"{b[i]} is the next the multiplier at position b[{7 - i}]") # debug c = 0 for j in range(7, -1, -1): # this process is performing a = a + a .. ie a = 2a, shifting to the left by 1 a[j], c = add_bit(a[j], a[j], c) # print(a, end=' a in this step after shifting\n') c = 0 for j in range(7, -1, -1): result[j], c = add_bit(result[j], a[j], c) # adding the shifted a to the result else: # else just shift a c = 0 for j in range(7, -1, -1): a[j], c = add_bit(a[j], a[j], c) print('\n') print('Multiplication result = ', result) print('\n') fig, (plot_a, plot_b, plot_result) = plt.subplots(3, 1) plot_a.plot(copy_a, 'g') plot_b.plot(copy_b, 'r') plot_result.plot(result) plot_result.set_xlabel('Result after multiplication') plt.show() def ands(a, b): if a == 1 and b == 1: return 1 else: return 0 def xors(a, b): if a != b: return 1 else: return 0 def ors(a, b): if a == 0 and b == 0: return 0 else: return 1 def add_bit(a, b, c): res = xors(xors(a, b), c) car = ors(ands(a, b), ands(xors(a, b), c)) return res, car def binary_4bit_num(num: str): if len(num) > 4: raise ValueError('Input a four bit number') num = num.zfill(4) # return flipped binary (that is the LSB is in the front) return ''.join([__is_bit__(i) for i in num.strip()]) def __is_bit__(num: str): bit = int(num) if bit > 1: raise ValueError('input is not a binary input') else: return str(bit)
5f2d916e536f3b8b8cf0610a37c52b2a13938a8a
BW1ll/PythonCrashCourse
/python_work/Chapter_9/9.1-9.3.py
2,138
4.5625
5
''' Python Crash Course - chapter 9 - Classes [Try it your self exercises] ''' # 9.1 class Restaurant: ''' example Restaurant Class in python using a generic details a bout Restaurants to build an example class ''' def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(f'{self.restaurant_name.upper()} serves {self.cuisine_type.title()}') def open_restaurant(self): print(f'{self.restaurant_name.upper()} is open.') # restaurant = Restaurant("Larry's Pizza", 'Pizza') # # restaurant.describe_restaurant() # restaurant.open_restaurant() # 9.2 r1 = Restaurant("larry's pizza", 'pizza') r2 = Restaurant('olive garden', 'italian') r3 = Restaurant("homer's", 'southern style\n') r1.describe_restaurant() r2.describe_restaurant() r3.describe_restaurant() # 9.3 class User: ''' User Class example example python Class for a general user in a general system ''' def __init__(self, first_name, last_name, birthday): self.first_name = first_name self.last_name = last_name self.name = f'{self.first_name.title()} {self.last_name.title()}' self.email = f'{self.first_name.lower()}.{self.last_name.lower()}@example.com' self.birthday = birthday def describe_user(self): user_description_message = f'Users current information: \n' user_description_message += f'\tUsers name: {self.name}\n' user_description_message += f'\tUsers email: {self.email.lower()}\n' user_description_message += f'\tUsers birthday: {self.birthday}' print(user_description_message) def greet_user(self): greeting = f'Hello {self.name}\n' print(greeting) u1 = User('brian', 'willis', '03-03-1978') u2 = User('rob', 'staggs', '03-17-1978') u3 = User('matt', 'kesterson', '04-17-1978') u4 = User('sarah', 'willis', '03-27-1978') u1.describe_user() u1.greet_user() u2.describe_user() u2.greet_user() u3.describe_user() u3.greet_user() u4.describe_user() u4.greet_user()
af668c9031314257aa1328b5689cf8e64805fe67
BW1ll/PythonCrashCourse
/python_work/Chapter 5/5.3-5.7.py
2,209
3.703125
4
''' 5.3 exersize ''' alien_color = 'green' if alien_color == 'green': print('You shot down a green aline and erned 5 points. 5.3') if alien_color == 'yellow': print('You shot down a yellow alien and erned 5 points. 5.3') ''' 5.4 exersize ''' alien_color = 'yellow' if alien_color == 'green': print('You shot down a green aline and erned 5 points. 5.4.1') elif alien_color == 'yellow': print('You shot down a yellow aline and erned 10 points.5.4.1') alien_color = 'red' if alien_color == 'green': print('You shot down a green aline and erned 5 points. 5.4.2') elif alien_color == 'yellow': print('You shot down a yellow aline and erned 10 points.5.4.2') ''' 5.5 exersize ''' alien_color = 'red' if alien_color == 'green': print('You shot down a green aline and erned 5 points. 5.5.1') elif alien_color == 'yellow': print('You shot down a yellow aline and erned 10 points. 5.5.1') else: print('You shot down a red alien and erned 15 points. 5.5.1') alien_color = 'green' if alien_color == 'green': print('You shot down a green aline and erned 5 points. 5.5.2') elif alien_color == 'yellow': print('You shot down a yellow aline and erned 10 points. 5.5.2') else: print('You shot down a red alien and erned 15 points. 5.5.2') alien_color = 'yellow' if alien_color == 'green': print('You shot down a green aline and erned 5 points. 5.5.3') elif alien_color == 'yellow': print('You shot down a yellow aline and erned 10 points. 5.5.3') else: print('You shot down a red alien and erned 15 points. 5.5.3') ''' 5.6 exersize ''' age = 40 if age < 2: stage = 'baby' elif age < 4: stage = 'toddler' elif age < 13: stage = 'kid' elif age < 20: stage = 'teenager' elif age < 65: stage = 'adult' else: stage = 'elder' print(f'This person is a {stage}') ''' 5.7 ''' fruit = ['apple', 'orange', 'banana'] if 'apple' in fruit: print('I hate apples!') if 'orange' in fruit: print('I hate oranges!') if 'banana' in fruit: print('I hate bananas!') if 'crakers' in fruit: print('I hate fruit!') if 'chcolate' in fruit: print('I hate fruit!')
005e54a5ee815a416767a4bb17f8d0cb6fe2b80f
BW1ll/PythonCrashCourse
/python_work/Chapter_9/9.6-9.8.py
6,175
4.65625
5
''' Python Crash Course - chapter 9 - Classes Try it your self exercises ''' # 9.6 class Restaurant: ''' example Restaurant Class in python using a generic details a bout Restaurants to build an example class ''' def __init__(self, restaurant_name, cuisine_type): '''initialize attributes to describe restaurant''' self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): '''return a neatly formated description of restaurant''' print(f'{self.restaurant_name.upper()} serves {self.cuisine_type.title()}') def open_restaurant(self): '''returns restaurant is open message''' print(f'{self.restaurant_name.upper()} is open.') def set_number_served(self, set): ''' returns message with the number of people served''' self.number_served = set print(f'{self.restaurant_name.upper()} has hosted {self.number_served} people.') def increment_number_served(self, set): self.number_served += set print( f'{self.restaurant_name.upper()} has hosted {self.number_served} people as of today.') class IceCreamStand(Restaurant): '''represents a specific typ of restaurant in the Restaurant Class''' def __init__(self, restaurant_name, cuisine_type='Ice Cream Stand'): '''Initialize attributes of the parent class.''' super().__init__(restaurant_name, cuisine_type='Ice Cream Stand') self.cuisine_type = 'Ice Cream Stand' self.flavors = ['vanila', 'chocolate', 'rocky road', 'mint chocolate chip', 'chocolate chip cookie dough'] def show_flavors(self): '''method to list flavors''' message = f'We have the following flavors: \n' for flavor in self.flavors: message += f'\t{flavor}\n' print(message) # scoop_dog = IceCreamStand('scoop dog') # scoop_dog.show_flavors() # 9.7 #class User: # ''' # User Class example # # example python Class for a general user in a general system # ''' # # def __init__(self, first_name, last_name, birthday): # '''initialize attributes to describe any user''' # self.first_name = first_name # self.last_name = last_name # self.name = f'{self.first_name.title()} {self.last_name.title()}' # self.email = f'{self.first_name.lower()}.{self.last_name.lower()}@example.com' # self.birthday = birthday # self.login_attempts = 0 # # def describe_user(self): # '''return a neatly formated description of a user instance''' # user_description_message = f'Users current information: \n' # user_description_message += f'\tUsers name: {self.name}\n' # user_description_message += f'\tUsers email: {self.email.lower()}\n' # user_description_message += f'\tUsers birthday: {self.birthday}' # print(user_description_message) # # def greet_user(self): # '''returns a simple user instance greatting''' # greeting = f'Hello {self.name}\n' # print(greeting) # # def increment_login_attempts(self): # '''increments the login_attempts varable''' # self.login_attempts += 1 # # def rest_login_attempts(self): # '''resets the login_attempts varable to 0''' # self.login_attempts = 0 # class Admin(User): # '''special user Admin that inherits from User class''' # # def __init__(self, first_name, last_name, birthday): # super().__init__(first_name, last_name, birthday) # self.privileges = ['add post', 'delete post', 'pin post', # 'ban user', 'modify user', 'mange privileged users'] # # def show_privileges(self): # message = f'Admin user {self.name.title()} can perform the following tasks: \n' # for item in self.privileges: # message += f'\t{item}\n' # print(message) # admin1 = Admin('brian', 'willis', '03-03-1978') # admin1.show_privileges() # 9.8 class Privileges: '''special user Admin that inherits from User class''' def __init__(self): self.privileges = ['add post', 'delete post', 'pin post', 'ban user', 'modify user', 'mange privileged users'] def show_privileges(self): message = f'Admin user can perform the following tasks: \n' for item in self.privileges: message += f'\t{item}\n' print(message) class User: ''' User Class example example python Class for a general user in a general system ''' def __init__(self, first_name, last_name, birthday): '''initialize attributes to describe any user''' self.first_name = first_name self.last_name = last_name self.name = f'{self.first_name.title()} {self.last_name.title()}' self.email = f'{self.first_name.lower()}.{self.last_name.lower()}@example.com' self.birthday = birthday self.login_attempts = 0 def describe_user(self): '''return a neatly formated description of a user instance''' user_description_message = f'Users current information: \n' user_description_message += f'\tUsers name: {self.name}\n' user_description_message += f'\tUsers email: {self.email.lower()}\n' user_description_message += f'\tUsers birthday: {self.birthday}' print(user_description_message) def greet_user(self): '''returns a simple user instance greatting''' greeting = f'Hello {self.name}\n' print(greeting) def increment_login_attempts(self): '''increments the login_attempts varable''' self.login_attempts += 1 def rest_login_attempts(self): '''resets the login_attempts varable to 0''' self.login_attempts = 0 class Admin(User): '''special user Admin that inherits from User class''' def __init__(self, first_name, last_name, birthday): super().__init__(first_name, last_name, birthday) self.privileges = Privileges() admin2 = Admin('brian', 'willis', '03-03-1978') admin2.privileges.show_privileges()
4e2f61a2c1986b72afd93ae90539df806f580e87
shackett/Drosophila_metabolism
/meta.rxns.writer.py
2,598
3.578125
4
import re import sys class ReactionCompound: """Represents a compound combined with its stoichiometry""" def __init__(self, name, number=1): """ Initialized with the name of the compound and optionally the number of molecules it has in a formula """ self.name = name self.number = number def __str__(self): if self.number > 1: return str(self.number) + " " + self.name else: return "\"" + self.name + "\"" class Enzyme: """Represents an enzyme and the reaction that it catalyzes""" def __init__(self, name, reversible=True): self.name = name self.reactants = [] self.products = [] self.reversible = reversible def add_reactant(self, reactant): self.reactants.append(reactant) def add_product(self, product): self.products.append(product) def __str__(self): ret = "\"" + self.name + "\": " ret += " + ".join(map(str, self.reactants)) if self.reversible: ret += " <=> " else: ret += " -> " ret += " + ".join(map(str, self.products)) return ret mycompound = ReactionCompound("pseudochemicaline", 3) myenzyme = Enzyme("pseudoenzymine") myenzyme.add_reactant(ReactionCompound("A", 3)) myenzyme.add_reactant(ReactionCompound("B")) myenzyme.add_product(ReactionCompound("C", 2)) myenzyme2 = Enzyme("pseudoenzymine") myenzyme2.add_reactant(ReactionCompound("A", 3)) myenzyme2.add_reactant(ReactionCompound("B")) myenzyme2.add_product(ReactionCompound("C", 4)) ######## write a system of reaction equations to be read by Omix using reaction output from R ###### Rreactions = open('meta.rxns.tsv','r') enzymes = [] for line in Rreactions: rxn = re.compile('reaction') react = re.compile('reactant') prod = re.compile('product') terms = line.split("\t") if rxn.search(line): if terms[2] == '1': reversible = False else: reversible = True enzymes.append(Enzyme(terms[1], reversible)) elif react.search(line): current_enzyme = enzymes.pop() current_enzyme.add_reactant(ReactionCompound("".join(["\"", terms[1], "\"", "[", terms[3][0], "]"]), terms[2])) enzymes.append(current_enzyme) elif prod.search(line): current_enzyme = enzymes.pop() current_enzyme.add_product(ReactionCompound("".join(["\"", terms[1], "\"", "[", terms[3][0], "]"]), terms[2])) enzymes.append(current_enzyme) rxn_eqtn = open('reaction_equations','w') for enzyme in enzymes: rxn_eqtn.write("%s\n" % (enzyme)) rxn_eqtn.close()
8be4c686a69c1e4a9d1fc1fcea5007775b0344b2
YonErick/d-not-2021-2
/data/lib/queue.py
2,543
4.3125
4
class Queue: """ ESTRUTURAS DE DADOS FILA - Fila é uma lista linear de acesso restrito, que permite apenas as operações de enfileiramento (enqueue) e desenfileiramento (dequeue), a primeira ocorrendo no final da estrutura e a segunda no início da estrutura. - Como consequência, a fila funciona pelo princípio FIFO (First In, First Out - primeiro a entrar, primeiro a sair). - A principal aplicação das filas são tarefas que envolvem o processamento de tarefas por ordem de chegada. """ """ Construtor da classe """ def _init_(self): self.__data = [] # Inicializa uma lista privada vazia """ Método para inserção O nome do método para inserção em filas é padronizado: enqueue() """ def enqueue(self, val): self.__data.append(val) # Insere no final da fila """ Método para retirada O nome do método de retirada em filas também é padronizado: dequeue() """ def dequeue(self): if self.is_empty(): return None # Retira e retorna o primeiro elemento da fila return self.__data.pop(0) """ Método para consultar o início da fila (primero elemento), sem retirá-lo Nome padronizado: peek() """ def peek(self): if self.is_empty(): return None return self.__data[0] """ Método para verificar se a fila está vazia ou não Retorna True se vazia ou False caso contrário """ def is_empty(self): return len(self.__data) == 0 """ Método que exibe a fila como uma string (para fins de depuração) """ def to_str(self): string = "" for el in self.__data: if string != "": string += ", " string += str(el) return "[ " + string + " ]" ############################################################################ fila = Queue() # Cria uma nova fila print(fila.to_str()) # Adicionando pessoas à fila fila.enqueue("Marciovaldo") fila.enqueue("Gildanete") fila.enqueue("Terencionildo") fila.enqueue("Junislerton") fila.enqueue("Ritielaine") print(fila.to_str()) atendido = fila.dequeue() print(f"Atendido: {atendido}") print(fila.to_str()) atendido = fila.dequeue() print(f"Atendido: {atendido}") print(fila.to_str()) fila.enqueue("Adenoirton") print(fila.to_str()) proximo = fila.peek() print(f"Próximo a ser atendido: {proximo}") print(fila.to_str())
9c94d150bd2c3bc4f6727122d2d6d34617609686
YonErick/d-not-2021-2
/data/02_busca_binaria.py
3,035
3.796875
4
# Algoritimo de Busca Binária # # Dada uma lista, que deve estar PREVIAMENTE ORDENADA, e um valor de # busca, divide a lista em duas metades e procura pelo valor de busca # apenas na metade onde o valor poderia estar. Novas subdivisões são # feitas até que se encontre o valor de busca ou que reste apenas uma # sublista vazia, quando se conclui que o valor de busca não existe na # lista. from time import time from lista_nomes import nomes comps = 0 # Declarando uma variável global def busca_binaria(lista, valor_busca): """ Função que implementa o algoritmo de busca binária Retorna a posição onde valor_busca foi encontrado ou o valor convencional -1 se valor_busca não existir na lista """ global comps # Indica que estamos usando a variável declarada na linha 13 comps = 0 ini = 0 # Primeira posição fim = len(lista) -1 # Ultima Posição while ini <= fim: meio = (ini + fim) // 2 # Operador // é divisão inteira # Caso 1: lista[meio] é igual a valor_busca if lista[meio] == valor_busca: # ENCONTROU! comps += 1 return meio # Meio é a posição onde valor_busca está na lista # Caso 2: valor_busca é menor que lista[meio] elif valor_busca < lista[meio]: comps += 2 fim = meio -1 # Descarta a 2 metade da lista # Caso 3: valor_busca é maior que lista[meio]~ else: comps += 2 ini = meio + 1 # Descarta a 1 metade da lista # Caso 4: valor_busca não encontrado na lista return -1 comps = 0 hora_ini = time() print(f"Posição de ERICK: {busca_binaria(nomes, 'ERICK')}") hora_fim = time() print(f"Tempo gasto procurando ERICK: {(hora_fim - hora_ini) * 1000}ms") hora_ini = time() print(f"Posição de ZULEICA: {busca_binaria(nomes, 'ZULEICA')}") hora_fim = time() print(f"Tempo gasto procurando ZULEICA: {(hora_fim - hora_ini) * 1000}ms") hora_ini = time() print(f"Posição de ORKUTILSON: {busca_binaria(nomes, 'ORKUTILSON')}") hora_fim = time() print(f"Tempo gasto procurando ORKUTILSON: {(hora_fim - hora_ini) * 1000}ms") hora_ini = time() print(f"Posição de BELERINA: {busca_binaria(nomes, 'BELERINA')}") hora_fim = time() print(f"Tempo gasto procurando BELERINA: {(hora_fim - hora_ini) * 1000}ms") hora_ini = time() print(f"Posição de LUNISVALDO: {busca_binaria(nomes, 'LUNISVALDO')}") hora_fim = time() print(f"Tempo gasto procurando LUNISVALDO: {(hora_fim - hora_ini) * 1000}ms") print(f"Nome exatamente no meio da lista: {nomes[len(nomes) // 2]} ") hora_ini = time() print(f"Posição de JERDERSON: {busca_binaria(nomes, 'JERDERSON')}, {comps} comparações ") hora_fim = time() print(f"Tempo gasto procurando JERDERSON: {(hora_fim - hora_ini) * 1000}ms") hora_ini = time() print(f"Posição de AARAO: {busca_binaria(nomes, 'AARAO')}, {comps} comparações ") hora_fim = time() print(f"Tempo gasto procurando AARAO: {(hora_fim - hora_ini) * 1000}ms")
0ef7995dbfc5ffa785a88d5456771876897cdcd0
spentaur/DS-Unit-3-Sprint-1-Software-Engineering
/sprint/acme_report.py
1,610
4.125
4
from random import randint, uniform, choice from acme import Product # Useful to use with random.sample to generate names ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(num_products=30): """Generate random Products Keyword Arguments: num_products {int} -- number of products to generate (default: {30}) Returns: list -- a list of the randomly generated products """ products = [] for _ in range(num_products): name = f"{choice(ADJECTIVES)} {choice(NOUNS)}" price = randint(5, 100) weight = randint(5, 100) flammability = uniform(0.0, 2.5) products.append(Product(name, price, weight, flammability)) return products def inventory_report(products): """Create a report from a list of Products""" prices_total = 0 weights_total = 0 flammability_total = 0 product_names = set() num_of_products = len(products) for product in products: prices_total += product.price weights_total += product.weight flammability_total += product.flammability product_names.add(product.name) print("ACME CORPORATION OFFICIAL INVENTORY REPORT") print("Unique product names: ", len(product_names)) print("Average price: ", prices_total / num_of_products) print("Average weight: ", weights_total / num_of_products) print("Average flammability: ", flammability_total / num_of_products) if __name__ == '__main__': inventory_report(generate_products())
300a9b8b8b4bcfe4d1070bfdfc814574b55ecce8
bourriquet/hackerrank
/30DaysOfCode/day18_queuesAndStacks/queuesAndStacks2.py
793
3.59375
4
import sys class Solution: def __init__(self): self.s = [] self.q = [] def pushCharacter(self, ch): self.s.append(ch) def enqueueCharacter(self, ch): self.q.append(ch) def popCharacter(self): return self.s.pop() def dequeueCharacter(self): return self.q.pop(0) s = raw_input() obj = Solution() l = len(s) for i in range(l): obj.pushCharacter(s[i]) obj.enqueueCharacter(s[i]) isPalindrome=True for i in range(l/2): if obj.popCharacter() != obj.dequeueCharacter(): isPalindrome = False break if isPalindrome: sys.stdout.write ("The word, " + s + ", is a palindrome.") else: sys.stdout.write ("The word, " + s + ", is not a palindrome.")
b1d1b348d8facec13ddcd00cf9b9098acf0c1bf3
j4s1x/crashcourse
/Projects/CrashCourse/oneMillion.py
336
3.765625
4
#make a list of the numbers 1 to 1 million, then use a for loop to print the numbers #how about just up to 100 so I don't blow up my computer numbers=[] add=1 for i in range(0,100): numbers.append(add) add +=1 print (numbers) print (sum(numbers)) #or y=list(range(1,101)) print (y) print(sum(y)) x = list(range(1,6)) print (x)
7202e752d0907a36648cc13282e113689117c0c5
j4s1x/crashcourse
/Projects/CrashCourse/Names.py
572
4.125
4
#store the names of your friends in a list called names. #print each person's name in the list #by accessing each element in the list, one at a time friends = ["you", "don't", "have", "any", "friends"] print (friends[0]) print (friends[1]) print (friends[2]) print (friends[3]) print (friends[4]) #So that was one long complicated annoying way to type a lot of code #let's try this way instead it was easier def FriendList(x): for i in range(0,5): print (friends[x]) x += 1 FriendList(0) #way less complicated. And in a cute little function too :)
2a53c61a3b1a235e4721983b872a9785ce3db31f
j4s1x/crashcourse
/Projects/CrashCourse/slices.py
626
4.28125
4
#Print the first three, the middle 3, and the last three of a list using slices. animals = ['cat', 'dog', 'cow', 'horse', 'sheep', 'chicken', 'goat', 'pig', 'alpaca'] print(animals[:3]) print(animals[3:6]) print(animals[-3:]) #Let's make a copy of that list. One list will be my animals, the other will be a friend's animals #add a new animal to the friends list but not mine. buddyAnimals = animals[:] animals.append('lion') buddyAnimals.append('Unicorn') print(animals) print(buddyAnimals) #print these lists using a for loop index = len(animals)-1 print(index) for i in range(0,index): print(animals[i], end='*')
95574484bf6a54088492ae1e69dd2d5f4babb155
j4s1x/crashcourse
/Projects/CrashCourse/polling.py
669
4.40625
4
# make a list of people who should take the favorite languages poll #Include some names in the dictionary and some that aren't #loop through the list of people who should take the poll #if they have taken it, personally thank them #elif tell them to take the poll favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } friends = ['john cleese', 'terry gilliam', 'michael palin', 'jen', 'sarah', 'edward', 'phil'] for name in friends: if name in favorite_languages: print (name.title() + ' has taken the poll. Thank you very much') elif name not in favorite_languages: print(name.title() + ' needs to take the poll!')
e80dbd61d099540b05ef8366e859cb4c66c7ca6a
j4s1x/crashcourse
/Projects/CrashCourse/rivers.py
643
4.65625
5
#list rivers and the provinces they run through. Use a loop to print this out. #Also print the river and provinces individually rivers = { 'MacKenzie River': 'Northwest Territories', 'Yukon River': 'British Columbia', 'Saint Lawrence River': 'Ontario', 'Nelson River': 'Manitoba', 'Saskatchewan River': 'Saskatchewan', } for river, province in rivers.items(): print('The ' + river + ' flows through ' + province) print('The following is the list of rivers from the dictionary:') for river in rivers: print(river) print('The following is the list of provinces from the dictionary') for province in rivers.values(): print(province)
602ded7ccd367e8a8f1fe3e3cdc389eb932a0ced
Gaskill/Python-Practice
/Spirit.py
662
4.21875
4
#find your spirit animal animals = ["Horse", "Pig", "Kangaroo", "Whale", "Pony", "Lobster", "Chicken", "Seahorse", "Wolf", "Bat", "Tiger", "Lion", "Pufferfish", "Swan", "Bear", "Pigeon", "Salamander", "Iguana", "Lizard", "Bee", "Crow", "Beetle", "Ant", "Elk", "Deer", "Jellyfish", "Fly", "Parrot", "Hamster", "Cow"] print("Find your spirit animal!") print(len(animals)) #prints number of animals in list choice = input("Pick a number 1 though 30.") #gathers player's input choice_int = int(choice)-1 #matches the number picked with an index from the list print(choice) #prints the number they chose print("Your spirit animal is a(n) %s!" %(animals[choice_int]))
e6c0429665fe1d99b2ebd257af5d5588faf76c09
Gaskill/Python-Practice
/tuples.py
223
3.71875
4
# Tuples can't be changed or sorted or rearranged season = ("Winter", "Summer", "Spring", "Fall") print(season) season.sort() #sport = ("Basketball", "Soccer", "Tennis", "Volleyball") #print(sport) #print(sport + season)
40994d6f1d2e3d74e93020bac996355fd6625986
ShijiZ/Python_Learning
/Crossin/Crossin55.py
347
3.8125
4
import re text='Hi, I am Shirlry Hilton. I am his wife.' m=re.findall(r'hi',text) if m: print m else: print 'not match' m=re.findall(r'\bhi',text) if m: print m else: print 'not match' m=re.findall(r'[Hh]i',text) if m: print m else: print 'not match' m=re.findall(r'\b[Hh]i',text) if m: print m else: print 'not match'
01764628721318f334596296a5cf0990d4f8eb1c
ShijiZ/Python_Learning
/Crossin/Crossin12_HW904.py
125
3.5625
4
a=1 b=0 while a<=100: b=b+a a+=1 print b #or a=1 b=0 for i in range(1,101): b=b+a a=a+1 print b
3fdd89683d8b13306e9701998373b85f20ac66d4
royan2024/Algorithm_Practice
/Sorting/SelectionSort.py
724
3.75
4
# selection sort template def find_min_number(l: list) -> int: m = l[0] for a in l: if m > a: m = a return m def selection_sort(l: list): sorted_list = [] while len(l) > 0: # find min number m = find_min_number(l) # remove from original list l.remove(m) # insert to sorted list sorted_list.append(m) return sorted_list def selection_sort_in_place(l: list): for i in range(len(l)): m = i for j in range(i, len(l)): if l[m] > l[j]: m = j l[m], l[i] = l[i], l[m] if __name__ == "__main__": l = [3, 7, 8, 5, 2, 1, 5, 9, 4] selection_sort_in_place(l) print(l)
bb3a36f70e072da652871264ff54225fdb7641b8
Obaydahm/4sem-python-handins
/week 4 - numpy/ex/ex1.py
2,966
3.9375
4
import matplotlib.pyplot as plt import numpy as np import csv # Week 4 Exercise with Numpy # Exercise 1 # 1. Open the file './befkbhalderstatkode.csv' filename = "../../befkbhalderstatkode.csv" # 2. Turn the csv file into a numpy ndarray with np.genfromtxt(filename, delimiter=',', dtype=np.uint, skip_header=1) data = np.genfromtxt(filename, delimiter=",", dtype=np.uint, skip_header=1) # 3. Using this data: neighb = { 1: "Indre By", 2: "Østerbro", 3: "Nørrebro", 4: "Vesterbro/Kgs. Enghave", 5: "Valby", 6: "Vanløse", 7: "Brønshøj-Husum", 8: "Bispebjerg", 9: "Amager øst", 10: "Amager Vest", 99: "Udenfor", } ## Find out how many people lived in each of the 11 areas in 2015 def number_of_people_per_neighbourhood(n, mask): all_people_in_given_n = data[mask & (data[:, 1] == n)] sum_of_people = all_people_in_given_n[:, 4].sum() # index 4 is no of 'PERSONER' return sum_of_people mask = data[:, 0] == 2015 neighborhoods_population_in_2015 = { v: number_of_people_per_neighbourhood(k, mask) for k, v in neighb.items() } # print(neighborhoods_population_in_2015) # 4. Make a bar plot to show the size of each city area from the smallest to the largest def draw_barplot(areas): areas = {k: v for k, v in sorted(areas.items(), key=lambda x: x[1])} x_neighb_names = areas.keys() y_neighb_population = areas.values() plt.bar(x_neighb_names, y_neighb_population) plt.title("Population of 11 areas in 2015") plt.xlabel("Areas") plt.ylabel("Population") plt.tight_layout() plt.show() # draw_barplot(neighborhoods_population_in_2015) # 5. Create a boolean mask to find out how many people above 65 years lived in Copenhagen in 2015 # 6. How many of those were from the other nordic countries (not dk) def people_above_65(): statcodes_nordic = [5110, 5120, 5104, 5105, 5106, 5101, 5901, 5902] filtered_data = data[ (data[:, 0] == 2015) & (data[:, 2] > 65) & (np.in1d(data[:, 3], statcodes_nordic)) ] return filtered_data[:, 4].sum() # print(people_above_65()) # 7. Make a line plot showing the changes of number of people in vesterbro and østerbro from 1992 to 2015 def changes_of_people(): years = [y for y in range(1992, 2016)] x_indexes = np.arange(len(years)) vesterbro = { k: number_of_people_per_neighbourhood(4, data[:, 0] == k) for k in years } østerbro = { k: number_of_people_per_neighbourhood(2, data[:, 0] == k) for k in years } width = 0.35 plt.bar(x_indexes, list(vesterbro.values()), width=width, label="Vesterbro") plt.bar(x_indexes + width, list(østerbro.values()), width=width, label="Østerbro") plt.legend() plt.xticks(ticks=x_indexes, labels=years) plt.title("Changes of people in Vesterbro and Østerbro from 1992 to 2015") plt.xlabel("Areas") plt.ylabel("Population") plt.tight_layout() plt.show() changes_of_people()
7b478cb0bed4930dcc56acc6f344cbd831d3c73a
Venismendes/jogo-do-dado
/jogo do dado.py
7,317
3.734375
4
import random player1_points = 1000 player2_points = 1000 dado = (1, 2, 3, 4, 5, 6) players = 1 player = input('Olá qual o seu nome: ') print(f'Bem vindo ao jogo do dado {player}') quantidade_jogadores = input('Deseja jogador de 2 jogadores? [S/N]: ').upper() if quantidade_jogadores == 'S': players = 2 player1 = player player2 = input('Nome do segundo jogador: ') print('=' * 40) while players == 1: print('Inicialmente você tem 1000 pontos!') print('[S] para sair!') print('[P] para ver seus pontos') print('[J] para jogar: ') while True: print('=' * 30) option = input('Opção: ').upper() print('=' * 30) while True: menu = True dice = random.choice(dado) if dice <= 3: value = 'L' else: value = 'H' if option == 'J': while True: try: if player1_points <= 0: print('Fim do jogo!!') exit() bet = int(input('Quantos pontos: ')) if bet <= 0 or bet > player1_points: print(f'O valor deve ser maior que 0, seus pontos são {player1_points}: ') else: low_high = input('|[L] = 123 | [H] = 456 | [S] = Sair: ').upper() break except ValueError: print('valor inválido, digite apenas números inteiros.') while low_high != 'H' and low_high != 'L' and low_high != 'S': print('Valor inválido') low_high = input('|[L] = 123 | [H] = 456 | [S] = Sair: ').upper() if low_high == value and (low_high == 'L' or low_high == 'H'): print(f'Você acertou e ganhou {bet} pontos!!') player1_points = player1_points + bet menu = False elif low_high == 'L' or low_high == 'H': print(f'Você errou e perdeu {bet} pontos!!') player1_points = player1_points - bet menu = False if low_high == 'S': menu = True break print() print(f'Dado: {dice} = {value}') print(f'Seus pontos: {player1_points}') print('=' * 30) if option == 'S': exit() if option == 'P': print(f'Você possui {player1_points} pontos.') if menu == True: print('=' * 30) option = input('Opção: ').upper() print('=' * 30) print('=' * 40) while players == 2: print('Inicialmente ambos tem 1000 pontos!') print('[S] para sair!') print(f'[P1] para ver seus pontos {player1}') print(f'[P2] para ver seus pontos {player2}') print('[J] para jogar: ') while True: print('=' * 30) option = input('Opção: ').upper() print('=' * 30) while True: menu = True dice = random.choice(dado) if dice <= 3: value = 'L' else: value = 'H' if option == 'J': while True: try: if player1_points <=0 or player2_points <=0: if player1_points <=0 and player2_points > 0: print(f'{player2} Venceu') if player2_points <=0 and player1_points > 0: print(f'{player1} Venceu') if player1_points <= 0 and player2_points <= 0: print('Empate') exit() break apostaj1 = int(input(f'Quantos pontos {player1}: ')) apostaj2 = int(input(f'Quantos pontos {player2}: ')) if apostaj1 <= 0 or apostaj1 > player1_points: print(f'{player1}O valor deve ser maior que 0, seus pontos são {player1_points}: ') if apostaj2 <= 0 or apostaj2 > player2_points: print(f'{player2}O valor deve ser maior que 0, seus pontos são {player1_points}: ') else: low_highj1 = input(f'{player1}|[L] = 123 | [H] = 456 | [S] = Sair: ').upper() low_highj2 = input(f'{player2}|[L] = 123 | [H] = 456 | [S] = Sair: ').upper() break except ValueError: print('valor inválido, digite apenas números inteiros.') while low_highj1 != 'H' and low_highj1 != 'L' and low_highj1 != 'S': print('Valor inválido') low_highj1 = input('|[L] = 123 | [H] = 456 | [S] = Sair: ').upper() while low_highj2 != 'H' and low_highj2 != 'L' and low_highj2 != 'S': print('Valor inválido') low_highj2 = input('|[L] = 123 | [H] = 456 | [S] = Sair: ').upper() if low_highj1 == value and (low_highj1 == 'L' or low_highj1 == 'H'): print(f'{player1} Você acertou e ganhou {apostaj1} pontos!!') player1_points = player1_points + apostaj1 menu = False elif low_highj1 == 'L' or low_highj1 == 'H': print(f'{player1} Você errou e perdeu {apostaj1} pontos!!') player1_points = player1_points - apostaj1 menu = False if low_highj2 == value and (low_highj2 == 'L' or low_highj2 == 'H'): print(f'{player2} Você acertou e ganhou {apostaj2} pontos!!') player2_points = player2_points + apostaj2 menu = False elif low_highj2 == 'L' or low_highj2 == 'H': print(f'{player2} Você errou e perdeu {apostaj2} pontos!!') player2_points = player2_points - apostaj2 menu = False if low_highj1 == 'S' or low_highj2 == 'S': menu = True break print() print(f'Dado: {dice} = {value}') print(f'{player1} Seus pontos: {player1_points}') print(f'{player2} Seus pontos: {player2_points}') print('=' * 30) if option == 'S': exit() player1_points = 1000 player2_points = 1000 if option == 'P1': print(f'{player1} possui {player1_points} pontos.') if option == 'P2': print(f'{player2} possui {player2_points} pontos.') if menu == True: print('=' * 30) option = input('Opção: ').upper() print('=' * 30)
6418e0d3be3936b9940a423abbc967fa4013afdc
asobhi1996/ID3DecisionTree
/main.py
7,914
3.703125
4
""" Main file for generating an ID3 tree from training data and performing accuracy tests on both training and test data Input: two command line arguments. First is a file with lableled training data and second is unlabeled test data. Training data includes up to N attributes and the last attribute must be the classification All input files will be in the following format. The first line will contain a tab-seperated list of attribute names. The reamining lines correspond to a labeled data instance, and consist of a tab-seperated list of 0s or 1s, corresponding to each attribute. Output: A decision tree object to classify data. The program will also outpout a visual representatino of the tree to the standard output and show training and test accuracy percentages. """ """ Psudocode: read data and create two lists of data objects (list of Training_object and Test_Ojbect) and an attribute list recursively create the tree using ID3 algorithm as defined print the tree to standard output test the tree with the training and test data and report accuracies """ import math,sys,random from Data import Data from Node import Node #recursive algorithm to generate a decision tree using ID3 def learn_tree(training_data,attributes): #base cases #there are no more data instances to classify if not training_data: return Node(classification = most_common_class) #this is a pure node, all data instances are of the same class if is_pure(training_data): return Node(classification = training_data[0].classification) #this is not a pure node, take the majority if not attributes: return Node(classification = majority_count(training_data)) #otherwise, we are in the recusive case and must split the data by an attribute #proceed to find the attribute that will yield the highest information gain best_attribute = learn_attribute(training_data,attributes) left,right = split_data(training_data,best_attribute) attributes.remove(best_attribute) splitting_attribute_node = Node(attribute=best_attribute) splitting_attribute_node.left = learn_tree(left,attributes) splitting_attribute_node.right = learn_tree(right,attributes) attributes.append(best_attribute) return splitting_attribute_node #split a list into 2 lists by attribute def split_data(data,attr): left,right = [],[] for instance in data: left.append(instance) if instance.attr_dict[attr] == 0 else right.append(instance) return left,right #function to determine if all instances of data have the same classification, returns true if pure, else false def is_pure(data): classification = data[0].classification for instance in data: if instance.classification != classification: return False return True #returns the majority classification 0 or 1 of a dataset def majority_count(data): positive_percent = len([True for instance in data if instance.classification == 1]) / float(len(data)) if positive_percent == .5: return most_common_class else: return 1 if positive_percent > .5 else 0 #algorithm for chosing attribute that will partition data with the lowest entropy def learn_attribute(data,attributes): lowest_entropy = 3 best_attribute = None for attr in attributes: conditional_entropy = conditional_entropy_calc(data,attr) if conditional_entropy < lowest_entropy: lowest_entropy = conditional_entropy best_attribute = attr elif conditional_entropy == lowest_entropy: if attribute_order_list.index(attr) < attribute_order_list.index(best_attribute): best_attribute = attr return best_attribute #formula for calculating the conditional distribution entropy of a dataset when partitioned by a particular attribute def conditional_entropy_calc(data,attribute): total = float(len(data)) left = [instance for instance in data if instance.attr_dict[attribute] == 0] right = [instance for instance in data if instance.attr_dict[attribute] == 1] left_entropy = entropy_calc(left) right_entropy = entropy_calc(right) return ((len(left)/total) * left_entropy) + ((len(right)/total) * right_entropy) #takes a distribution and calculates entropy def entropy_calc(data): if len(data) == 0: return 0 negative = 0.0 total = float(len(data)) for instance in data: if instance.classification == 0: negative += 1 negative_probability = negative/total positive_probability = (total-negative)/total if negative_probability == 0: left_entropy = 0 else: left_entropy = -1 * negative_probability * math.log(negative_probability,2) if positive_probability == 0: right_entropy = 0 else: right_entropy = -1 * positive_probability * math.log(positive_probability,2) return left_entropy + right_entropy #reads .dat file for training and test files, returns a list of attributes, list of training data objects, and list of test data objects def read_data(filename,filename2): attributes_read = False training_data,test_data = [],[] with open(filename) as data_file: for line in data_file: if line.isspace(): continue if not attributes_read: attribute_list = line.strip('\n').split('\t') #remove class "attribute" from attr list attribute_list = attribute_list[:-1] attributes_read = True else: val_lst = line.strip('\n').split('\t') training_data.append(Data(attribute_list,val_lst[:-1],val_lst[-1])) attributes_read = False with open(filename2) as data_file: for line in data_file: if line.isspace(): continue if not attributes_read: attributes_read = True else: val_lst = line.strip('\n').split('\t') test_data.append(Data(attribute_list,val_lst[:-1],val_lst[-1])) return attribute_list,training_data,test_data def print_decision_tree(decision_tree,depth): if decision_tree is None: print("ERROR") sys.exit() else: if not decision_tree.is_leaf(): if not decision_tree.left.is_leaf(): print("| " * depth,end='') if not decision_tree.left.is_leaf(): print('{} = 0 :'.format(decision_tree.attribute)) print_decision_tree(decision_tree.left,depth+1) else: print('{} = 0 :\t{}'.format(decision_tree.attribute,decision_tree.left.classification)) if not decision_tree.right.is_leaf(): print("| " * depth,end='') if not decision_tree.right.is_leaf(): print('{} = 1 :'.format(decision_tree.attribute)) print_decision_tree(decision_tree.right,depth+1) else: print('{} = 1 :\t{}'.format(decision_tree.attribute,decision_tree.right.classification)) else: print(decision_tree.classification) #function to test tree accuracy on a collection of data def test_tree_accuracy(decision_tree,test_data): correct = 0.0 for instance in test_data: if predicited_value(instance,decision_tree) == instance.classification: correct += 1 return correct / len(test_data) #given a tree and data, predicts the label of the data def predicited_value(instance,tree): if tree.classification is not None: return tree.classification if instance.attr_dict[tree.attribute] == 0: return predicited_value(instance,tree.left) else: return predicited_value(instance,tree.right) #main function #reads data, learns the tree, tests accuracy, and prints to console if __name__ == "__main__": attribute_list,training_data,test_data = read_data(sys.argv[1],sys.argv[2]) most_common_class = majority_count(training_data + test_data) attribute_order_list = attribute_list.copy() decision_tree = learn_tree(training_data,attribute_list) print_decision_tree(decision_tree,0) print("Accuracy on training data ({} instances) is {:.2%}".format(len(training_data),test_tree_accuracy(decision_tree,training_data))) print("Accuracy on test data ({} instances) is {:.2%}".format(len(test_data),test_tree_accuracy(decision_tree,test_data)))
f3aaa00f37f0506030a18fc73804e9187beb7c99
Marlysson/AppEvents
/enums/tipo_atividade.py
343
3.546875
4
# -*- coding: utf-8 from enum import Enum class TipoAtividade(Enum): PALESTRA = "Palestra" TUTORIAL = "Tutorial" MINI_CURSO = "Mini Curso" MESA_REDONDA = "Mesa Redonda" WORKSHOP = "Workshop" HACKATHON = "Hackathon" COFFEE_BREAK = "Coffee Break" def __str__(self): return "{}".format(self.value)
769ccf78cdedae14fbf0639fe910748de6b696bb
Meowsers25/Project-Euler-Problems
/problem1.py
126
3.875
4
count = 0 for number in range (1, 1000): if number % 3 == 0 or number % 5 == 0: count = count + number print(count)
bb6ed1f4df8033a9088c37225de7efee7f0c66e2
zkmacdon/Collatz
/Collatz.py
919
4.03125
4
class Collatz: """ This class is designed for creating objects that possess a collatz conjecture value relevant to the inputted value. The collatz conjecture value is deifned by the number of cycles required when using the rules of the collatz conjecture for a number to arrive at 1. """ number: int _cycles: float def __init__(self, num: int): self.number = num self._cycles = 0 def make_tuple(self) -> tuple: return self.number, self._cycles def _dummy_collatz(self, num: float) -> None: # clean up this method. self._cycles += 1 if num == 1.0: pass else: if num % 2 == 0: self._dummy_collatz(num / 2) else: self._dummy_collatz(3 * num + 1) def run(self) -> float: num = self.number self._dummy_collatz(num) return self._cycles
75a232d1d0d4c6b0c0411bc0aac3f536038f43a0
marcosjr0816/Python
/simple-linked-list/simple_linked_list.py
1,422
3.9375
4
class Node(object): def __init__(self, value): self._value = value self._next = None def value(self): return self._value def next(self): return self._next class LinkedList(object): def __init__(self, values=[]): self._head = None for value in values: self.push(value) def __len__(self): length = 0 node = self._head while node: length += 1 node = node._next return length def head(self): if self._head: return self._head else: raise EmptyListException def push(self, value): new_head = Node(value) if self._head: new_head._next = self._head self._head = new_head def pop(self): if self._head: value = self._head.value() self._head = self._head._next return value else: raise EmptyListException def __iter__(self): self.iter_next = self._head return self def __next__(self): if self.iter_next: value = self.iter_next.value() self.iter_next = self.iter_next._next return value else: raise StopIteration def reversed(self): values = list(self) return LinkedList(values) class EmptyListException(Exception): pass
9db8334bbf1e16c3d146d0305526c73482fd740a
kyon0304/BaofoJiaoIMPL
/quicksort.py
1,437
3.78125
4
#!/usr/bin/python import random import time def unsorted(length): return [random.randrange(0, length*10) for r in xrange(length)] def quicksort(l): if len(l) > 0: pivot = random.randint(0, len(l)-1) elements = l[:pivot] + l[pivot+1:] left = [e for e in elements if e <= l[pivot]] right = [e for e in elements if e > l[pivot]] l = quicksort(left) + [l[pivot]] + quicksort(right) return l def qsort(L): if len(L) < 2: return L pivot = random.choice(L) small = [i for i in L if i < pivot] pivots = [i for i in L if i == pivot] large = [i for i in L if i > pivot] return qsort(small) + pivots + qsort(large) def compare(a, b): if a < b: return -1 if a == b: return 0 if a > b: return 1 def distribute(bins, L, fn): for item in L: bins[fn(item)].append(item) def qqsort(L): if len(L) < 2: return L pivot = random.choice(L) bins = {-1:[], 0:[], 1:[]} distribute(bins, L, lambda x : compare(x, pivot)) return qqsort(bins[-1]) + bins[0] + qqsort(bins[1]) if __name__ == '__main__': l = unsorted(10) print l start = time.time() l = quicksort(l) end = time.time() qsort(l) end2 = time.time() qqsort(l) end3 = time.time() print l print "sublist time:", (end - start), "originlist time:", (end2 - end), "go through once:", (end3 - end2)
172c116f9297e32e4d7cf4b6668970235a2bcb42
russellpipal/python-challenge
/python-challenge-3.py
203
3.890625
4
"""Python Challenge #3""" import re cont = open("challenge-3-text.txt").read() print(re.findall(r'[a-z][A-Z]{3}[a-z][A-Z]{3}[a-z]', cont)) # Works! Get all of the small letters and put them together.
fac86a8c9b665ae3eb7a88556b5856084e393805
cofren/Coding_Bootcamp
/Weeks/Week8/Day2/daily_challenge.py
3,909
4.625
5
""" Daily Challenge : Old MacDonald’s Farm Look carefully at this code and output File: market.py macdonald = Farm("McDonald") macdonald.add_animal('cow',5) macdonald.add_animal('sheep') macdonald.add_animal('sheep') macdonald.add_animal('goat', 12) print(macdonald.get_info()) Output McDonald's farm cow : 5 sheep : 2 goat : 12 E-I-E-I-0! Create the code that is needed to recreate the code above. Here are a few questions to help give you some direction: 1. Create a Farm class. How do we implement that? 2. Does the Farm class need an __init__ method? If so, what parameters should it take? 3. How many method does the Farm class need ? 4. Do you notice anything interesting about the way we are calling the add_animal method? What parameters should this function have? How many…? 5. Test that your code works and gives the same results as the example above. 6. Bonus: line up the text nicely in columns like in the example using string formatting Expand The Farm Add a method to the Farm class called get_animal_types. It should return a sorted list of all the animal types (names) that the farm has in it. For the example above, the list should be: ['cow', 'goat', 'sheep'] Add another method to the Farm class called get_short_info. It should return a string like this: “McDonald’s farm has cows, goats and sheep.” It should call the get_animal_types function. How would we make sure each of the animal names printed has a comma after it aside from the one before last (has an and after) and the last(has a period after)?. """ class Farm: def __init__(self, farmer_name): self.farmer_name = farmer_name self.animals = {} # self.animals is not dynamic, it is set as an empty dictionary by default def add_animal(self, animal, count=1): if animal in self.animals.keys(): # This will check if <animal> appear as a key in self.animals # 1) The animal already exit in the farm, we just want to add some self.animals[animal] += count else: # 2) There is no such animal yet, we need to add it to the dict and set the count to <count> self.animals[animal] = count def get_info(self): msg = "" msg += f"{self.farmer_name}'s Farm" + "\n" msg += "\n" for animal, count in self.animals.items(): msg += f"{animal}: {count}" + "\n" return msg macdonald = Farm("McDonald") macdonald.add_animal('cow', 5) macdonald.add_animal('sheep') macdonald.add_animal('sheep') macdonald.add_animal('goat', 12) print(macdonald.get_info()) # class Farm: # def __init__(self,farm_name): # print(f"{farm_name}'s Farm") # print("") # self.animal = "" # self.qty = 0 # self.all_animals=[] # def add_animal(self,animal,qty=1): # self.animal = animal # self.qty = qty # self.all_animals.append(self.animal) # print(f"{self.animal}: {self.qty}") # def get_animal_types(self): # print(sorted(self.all_animals)) # def get_short_info(self): # print("McDonald's farm has", ",".join(self.all_animals)) # def get_info(self): # return print("E-I-E-I-O") # macdonald = Farm("McDonald") # macdonald.add_animal("cow",5) # macdonald.add_animal("sheep") # macdonald.add_animal("sheep") # macdonald.add_animal("goat",12) # print(macdonald.get_info()) # macdonald.get_animal_types() # macdonald.get_short_info() # # class Dog(): # # Initializer / Instance Attributes # # def __init__(self, name_of_the_dog): # # print("A new dog has been initialized !") # # print("His name is", name_of_the_dog) # # self.name = name_of_the_dog # # def bark(self): # # print("{} barks ! WAF".format(self.name)) # # Dog1=Dog("Rex") # # Dog1.bark()
20974deca3f1f0e51818efdc86cfd6612fae40ca
cofren/Coding_Bootcamp
/Weeks/Week6/Day6/tc_2.py
123
3.828125
4
string = "You have entered a wrong domain" new_list = string.split(" ") print(new_list) new_list.reverse() print(new_list)
a13e7f5a36c690aee7e486d6c8d4bc6b943aa9a5
cofren/Coding_Bootcamp
/Weeks/Week6/Day4/xpGold.py
3,794
4
4
import string import random """ # Exercise 1 list1 = [1, 2, 3, 4] list2 = [6, 7, 8, 9] list1.extend(list2) print(list1) # Exercise 2 list = [] for i in range(1, 4): number = input("Please enter a number:") list.append(int(number)) print(list) print(f"The max number is {max(list)}") # Exercise 3 letter_string = string.ascii_lowercase for letter in letter_string: if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u": print(f"{letter} is a vowel") else: print(f"{letter} is a consonant") #Exercise 4 names = ['Samus', 'Cortana', 'V', 'Link', 'Mario', 'Cortana', 'Samus'] user = input("What´s your name?") if user in names: print(names.index(user)) else: print("not in") #Exercise 5 words = [] while len(words) < 7: word = input("Please enter a word:") words.append(word) print(words) letter = input("Please enter 1 single Character:") print(letter) for word in words: position = word.find(letter) if position != -1: print(f"Your Character is in position {position} of the word {word}") else: print(f"The letter {letter} is not in the word {word}") # Exercise 6 numbers = [] for number in range(1,1000001): numbers.append(number) print(numbers) print(max(numbers)) print(min(numbers)) print(sum(numbers)) # Exercise 7 string = input("Please enter some numbers, separated by comma:") new_list = string.split(",") new_tuple = tuple(new_list) print(new_list) print(new_tuple) # Exercise 8 user_number = "" random_number = random.randint(1,9) guess_counter = 0 guess_success = 0 guess_or_not = True print(random_number) user_number = int(input("Please enter a number between 1 and 9:")) while guess_or_not: guess_counter += 1 if user_number == random_number: guess_success += 1 guess_counter += 1 print("You guessed correct!") play_again = input("Want to play again? Enter \"y\\n\"") if play_again != "y": break else: user_number = int(input("Enter a number between 1 and 9:")) guess_or_not = True else: guess_counter += guess_counter play_again = input("Number was wrong. Want to play again? Enter \"y\\n\"") if play_again != "y": break else: user_number = int(input("Enter a number between 1 and 9:")) guess_or_not = True print(f"You guessed {guess_success} time(s) correct out of a total of {guess_counter} guesses") """ # Exercise 9 user_info = { "customer_name": "", "waiter": "", "item": "", "price": "", "qty": "", "discount": "" } user_info["customer_name"] = input("Whats your name?\n") user_info["waiter"] = input("Who was your waiter?\n") user_info["item"] = input("What did you order \n") user_info["price"] = input("What was the price? \n") user_info["qty"] = input("How many did you have?\n") user_info["discount"] = input("How much discount did you get?\n") total_charge = int(user_info["price"]) * int(user_info["qty"]) print(f"The total charge excluding VAT is ${total_charge}.\n Including VAT is ${total_charge * 1.16}. You had: \n blablabla ") print(user_info) # while guess_or_not == True: # if user_number == random_number: # print("Congrats you guessed the right number!") # guess_counter += 1 # break # else: # guess_or_not = input("Sorry, not the right number. If you want to guess again, please enter a number between 1 and 9. If you want to stop, please enter \"done\".") # print(f"You guessed {guess_counter} times until you hit the right number!") # letter = "g" # word = "dfsgdfsd" # position = word.index(letter) # print(position) # txt = "Hello, welcome to my world." # x = txt.index("welcome") # print(x)
a6715be49b6288c06f86e43eb48388609cfc199f
cofren/Coding_Bootcamp
/Weeks/Week7/Day2/xpNinja.py
1,310
4.0625
4
# Exercise 1 list_of_strings = [] def box_printer(strings): list_of_strings = string_to_list(strings) longest_word = longest_string(list_of_strings) stars_print = "".join(stars_top_bottom(longest_word)) add_spaces(longest_word,list_of_strings) print(list_of_strings) print(longest_word) print(stars_print) for rows in add_spaces: print(string_row) def string_to_list(strings): list_of_strings = strings.split(",") return list_of_strings def longest_string(list_of_strings): longest_string ="" for string in list_of_strings: if len(string) > len(longest_string): longest_string = string return longest_string def stars_top_bottom(longest_word): stars = ["*","*","*","*"] for letter in longest_word: stars.append("*") return stars def add_spaces(longest_word,list_of_string): for word in list_of_strings: letter_list = ["*"," "] for letter in word: letter_list.append(letter) letter_list.append(" ") letter_list.append("*") string_row = "".join(letter_list) return string_row strings = input("Please input words, separated by comma:") box_printer(strings) # print(list_of_strings) # print(longest_word) # print(stars_print)
57c1a5bbbc88a39ea0eefcba6f54fcc39a1ff57f
saranguruprasath/Python
/Python_Classes.py
501
4.1875
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 14 22:27:09 2018 @author: saran """ class Circle(): pi = 3.14 def __init__(self,radius=1): self.radius = radius self.area = radius * radius * Circle.pi def get_circumference(self): return 2 * self.pi * self.radius my_circle = Circle() my_circle1 = Circle(12) print(my_circle.area) print(my_circle.get_circumference()) print("\n"*2) print(my_circle1.area) print(my_circle1.get_circumference())
776fd3c7c8b548dfdb1c6c0689aedce170c683e3
saranguruprasath/Python
/test.py
187
4.0625
4
print ("Python test program") x=1 y=2 print ("X=",x) print ("Y=",y) y=x+y print ("Y=",y) if y == 2: print ("Y is not added with X") else: print ("X is added with Y and result is:",y)
ccae406d0cae6f39f78c1f71c9556c6d7c5d90b6
TheAwesomeAray/LearningPython
/Tutorial/Exceptions.py
548
4.09375
4
student = { "name": "Andrew", "student_id": 1, "grade": "A" } try: last_name = student["last_name"] except KeyError as error: print("Error! Could not find last name. {0}".format(error)) student["last_name"] = "Ray" try: last_name = student["last_name"] print(last_name) numbered_last_name = 3 + last_name except KeyError as error: print("Error! Could not find last name.") except TypeError as error: print("Error! Cannot add these types.") print(error) except Exception: print("Unknown Error!")
19add075be78bfdb8342d9b376aef36e82a804ca
joelpaula/Projeto-Final-EDA
/BinaryHeap.py
2,378
3.71875
4
class BinaryHeap(object): class _Node(object): def __init__(self, key, element): self._element = element self._key = key def __str__(self): return f"{self._key}: {self.element}" def __repr__(self): return str(self) def __init__(self): self._heap = [] def _len__(self): return len(self._heap) @staticmethod def _parent(position): return (position - 1)//2 @staticmethod def _left(position): return 2 * position + 1 @staticmethod def _right(position): return 2 * position + 2 def is_empty(self): return len(self._heap) == 0 def inspect_first(self): if self.is_empty(): return None return self._heap[0]._key, self._heap[0]._element def add(self, key, element): node = self._Node(key, element) self._heap.append(node) self._bubble_up(len(self._heap)-1) def first(self): k, v = self.inspect_first() last = self._heap.pop() if not self.is_empty(): self._heap[0] = last self._bubble_down(0) return k, v def _bubble_up(self, position): if position <= 0 : return parent_pos = self._parent(position) parent = self._heap[parent_pos] node = self._heap[position] if parent._key > node._key: self._swap(position, parent_pos) self._bubble_up(parent_pos) def _swap(self, a, b): o = self._heap[a] self._heap[a] = self._heap[b] self._heap[b] = o def _exists(self, position): return len(self._heap) > position def _bubble_down(self, position): left = self._left(position) right = self._right(position) # no left node = no right node = nothing to do here if not self._exists(left): return # print("Exists Right: ", self._exists(right), right) # print("Exists Left:", self._exists(left), left) if self._exists(right) and self._heap[left]._key > self._heap[right]._key: new_pos = right else: new_pos = left if self._heap[position]._key > self._heap[new_pos]._key: self._swap(position, new_pos) self._bubble_down(new_pos)
1a8bbdd1ca8376c7921452ff114c3d818829aa8c
tylersmithSD/Basic_Cryptography-Python
/Cryptography.py
5,855
4.5
4
#Developer: Tyler Smith #Date: 10.19.16 #Purpose: The program takes an english word that the user types in # and encrypts it, making it secret. The user also has # the option to take an encrypted word and decrypt it, # revealing its english translation. There is also an # additional choice the user has, randomizing # the encryption key. #Import library to randomize key import random #The menu function greets the user asking them what they want to do def menu(): print('\nSecret Decoder Menu') # Name of program print('0) Quit') # Ends program print('1) Encode') # Encode english word print('2) Decode') # Decode encrypted word print('3) Generate new key') # New key # See what the user would like to do userResponse = input('What would you like to do? ') return userResponse # Return user response #Encode function encrypts english word def encode(encodeText): encodeStr = True # Determines whether we should be looping or not encodeChar = '' # Character that we want to encrypt index = 0 # Position of encodeChar in alpha string keyChar = '' # Corresponding key character for encodeChar loopCount = -1 # Keeps track of how many characters we have encrypted endLoop = ((len(encodeText)) - 1)# This ensures we know when to stop looping output = '' # Defines variable output #Begin encoding string while encodeStr: loopCount = (loopCount + 1) # Keeps track of what character we are on in encodeText encodeChar = encodeText[loopCount]# Character that we want to encode encodeChar = encodeChar[0].upper()# Convert character to uppercase so we can encode if(encodeChar != ' '): # If character isn't a space, do this index = alpha.index(encodeChar) # Find position where encodeChar exists in alpha string keyChar = key[index] # Get corresponding encoded character output = (output + keyChar) # Set the output = to what we have + the new keyChar we just found else: # If character is a space, do this keyChar = '_' # Set keyChar = underscore so representing a space output = (output + keyChar) # Set the output = to what we have + the new keyChar we just found if(loopCount == endLoop): # If we are done encoding each string, end loop return output # Return what we encoded encodeStr = False # Change loop condition, so we exit loop #Decode encoded string def decode(decodeText): decodeStr = True # Determines whether we should be looping or not decodeChar = '' # Character that we want to decrypt index = 0 # Position of decodeChar in key string alphaChar = '' # Corresponding alpha character for decodeChar loopCount = -1 # Keeps track of how many characters we have encrypted endLoop = ((len(decodeText)) - 1)# This ensures we know when to stop looping output = '' # Defines variable output while decodeStr: loopCount = (loopCount + 1) # Keeps track of what character we are on in decodeText decodeChar = decodeText[loopCount]# Character that we want to decode decodeChar = decodeChar[0].upper()# Convert character to uppercase so we can decode if(decodeChar != '_'): # If character isn't a space, do this index = key.index(decodeChar) # Find position where decodeChar exists in key string alphaChar = alpha[index] # Get corresponding decoded character output = (output + alphaChar) # Set the output = to what we have + the new keyChar we just found else: # If character is an underscore, do this alphaChar = ' ' # Set alphaChar = to a space output = (output + alphaChar) # Set the output = to what we have + the new keyChar we just found if(loopCount == endLoop): # If we are done decoding each string, end loop return output # Return what we decoded decodStr = False # Change loop condition, so we exit loop #Randomize key string def randomizeKey(): keyRandom = ''.join(random.sample(key,len(key))) #Randomize it and store it as variable return keyRandom # Return what we randomize #Main processing of entire program def main(): global alpha # These variables need to be defined here as global global key # so they can be changed in the program alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Enlgish key of encrypted word key = "XPMGTDHLYONZBWEARKJUFSCIQV" # Encrypted key of english word keepGoing = True while keepGoing: response = menu() if response == "1": # User wants to encode text plain = input("Text to be encoded: ") print(encode(plain)) elif response == "2": # User wants to decode text coded = input("Code to be decyphered: ") print (decode(coded)) elif response == "3": key = randomizeKey() elif response == "0": # User wants program to end print ("Thanks for doing secret spy stuff with me.") keepGoing = False else: # User entered input wrong print ("I don't know what you want to do...") #Run main function main()
f05853737710c77bfd29ac96cc5e7ce193c2096d
pulakanamnikitha/phython
/min.py
226
3.875
4
min=int(raw_input()) def smallest(arr,n): min = arr[0] for i in range(1, n): if arr[i] > max: min = arr[i] return min arr = [1,2,3,4,5] n = len(arr) Ans = smallest(arr,n) print (Ans)
863c35eef66e54f90504b5bdd1dd4b572cc8a36c
pulakanamnikitha/phython
/731.py
105
3.5625
4
n=int(raw_input()) p,q=map(int,raw_input().split()) if p<n and n<q: print "yes" else: print "no"
4f98933bfd786c20739cf775e223dfee4d6f3466
darthbeep/list_password_strength
/list.py
789
3.765625
4
import string import math lower = string.lowercase upper = string.uppercase numbers = string.digits other = ".?!&#,;:-_*" def minimum(password): l = len([x for x in lower if x in password ]) > 0 u = len([x for x in upper if x in password ]) > 0 n = len([x for x in numbers if x in password ]) > 0 print l, u, n return l and u and n def strength(password): l = len([x for x in lower if x in password ]) u = len([x for x in upper if x in password ]) n = len([x for x in numbers if x in password ]) o = len([x for x in other if x in password ]) ret = math.sqrt(l) + math.sqrt(u) + math.sqrt(n) + math.sqrt(o) ret = ret * 10 / len(password) print ret return ret strength("abcD") strength("password") strength("helpM3!") strength("aBCd")
56e401213a3cc3b4fbc6cf581cf8565078c1fa57
JeromeTroy/PyMath
/Python/interp.py
9,829
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 8 11:35:24 2019 @author: jerome """ import numpy as np import matplotlib.pyplot as plt import ode def polyinterp(x_nodes, y_values, new_nodes): """ Polynomial interpolation using the second barycentric form Input: x_nodes - x nodes of original data y_values - original function values new_nodes - points to interpolate at Output: new_yvals - interpolated y values """ weights = np.ones(len(x_nodes)) for j in range(len(x_nodes)): for k in range(len(x_nodes)): if k == j: continue else: weights[j] /= (x_nodes[j] - x_nodes[k]) new_yvals = np.zeros(len(new_nodes)) for l in range(len(new_nodes)): if new_nodes[l] in x_nodes: new_yvals[l] = y_values[x_nodes == new_nodes[l]] else: numerator = np.sum(weights * y_values / (new_nodes[l] - x_nodes)) denominator = np.sum(weights / (new_nodes[l] - x_nodes)) new_yvals[l] = numerator / denominator return new_yvals def compute_mvalues(x_nodes, y_values, ends="natural"): """ Helper function for cubic splines - computes m values for computation Input: x_nodes - x nodes of original data y_values - y values of original data Optional - ends - default 'natural' if ends = [yp1, yp2], use those as the derivative values at the ends Output: mvals - m values (function as weights) """ n = len(x_nodes) # get spacings hvals = x_nodes[1:] - x_nodes[:-1] delta = np.zeros(n) delta[1:-1] = (y_values[2:] - y_values[1:-1]) / hvals[1:] - \ (y_values[1:-1] - y_values[:-2]) / hvals[0:-1] diag = np.ones(n) diag[1:-1] = 2 * (hvals[:-1] + hvals[1:]) upperdiag = np.copy(hvals) upperdiag[0] = 0 lowerdiag = np.copy(hvals) lowerdiag[-1] = 0 A = np.diagflat(diag) + np.diagflat(upperdiag, 1) + np.diagflat(lowerdiag, -1) if ends == "periodic": A[0, -1] = 1 A[-1, 0] = 1 if type(ends) == type(""): ends = ends.lower() if ends not in ["natural", "periodic"]: print("Warning, unknown ends specifier, interpreting as 'natural'") ends = "natural" elif type(ends) not in [type([]), type(np.array([]))]: print("Warning unknown type for ends specifier, interpreting as 'natural") ends = 'natural' else: [yp1, yp2] = ends delta[0] = yp1 - (y_values[1] - y_values[0]) / hvals[0] delta[-1] = yp2 - (y_values[-1] - y_values[-2]) / hvals[-1] A[0, :2] = [-2 * hvals[0], -hvals[0]] A[-1, -2:] = [hvals[-1], 2 * hvals[-1]] A /= 6 mvals = np.linalg.solve(A, delta) return mvals def compute_spline_coefs(mvals, hvals, y_values, ends=None): """ Helper for splines - compute standard coefficients Input: mvals - computed m weights for spline hvals - step sizes y_values - known y points of data Optional - ends - defaults to None - no change if is a list, uses these as the new yprime(x0) and yprime(xn) Output: coef1 coef2 coef3 These are the three coefficients in the spline is coef1 * (x - xi)^3 + coef2 * (x - xi)^2 + coef3 * (x - xi) """ coef1 = (mvals[1:] - mvals[:-1]) / (6 * hvals) coef2 = 0.5 * mvals[1:] coef3 = -coef1 * np.power(hvals, 2) + coef2 * hvals + \ (y_values[1:] - y_values[:-1]) / hvals #if type(ends) in [type([]), type(np.array([]))]: # print("here") # coef3[-1] = ends[-1] return [coef1, coef2, coef3] def cubespline(x_nodes, y_values, new_nodes, ends="natural"): """ Build cubic spline interpolant Input: x_nodes - x nodes of original data y_values - y values of original data new_nodes - new nodes to get data values Optional - ends - string "natural, periodic" indicates type of spline Natural spline - zero second derivative at ends Periodic spline - second derivative is periodic true_vals - true derivative values [yp1, yp2] - specificed derivative values at ends Output: new_values - new y values at new_nodes """ if ends == "true_vals": D = ode.diffmat(x_nodes, num_nodes=5) yprime_true = np.matmul(D, y_values) ends = [yprime_true[0], yprime_true[-1]] return cubespline(x_nodes, y_values, new_nodes, ends=ends) mvals = compute_mvalues(x_nodes, y_values, ends=ends) hvals = x_nodes[1:] - x_nodes[:-1] # build piecewise function [coef1, coef2, coef3] = compute_spline_coefs(mvals, hvals, y_values, ends=ends) new_values = np.zeros(len(new_nodes)) xsel = x_nodes[1:] ysel = y_values[1:] for j in range(len(new_nodes)): cur = new_nodes[j] index = (cur >= x_nodes[:-1]).astype(int) + (cur < x_nodes[1:]).astype(int) > 1 if (sum(index.astype(int))) == 0: index = -1 new_values[j] = coef1[index] * np.power(cur - xsel[index], 3) + \ coef2[index] * np.power(cur - xsel[index], 2) + \ coef3[index] * (cur - xsel[index]) + ysel[index] #for j in range(len(new_nodes)): # new_values[j] = np.piecewise(new_nodes[j], cond_list, fun_list) return new_values def splineder(x_nodes, y_values, new_nodes, ends="natural"): """ Compute the derivative of a function using its cubic spline Input: x_nodes - x nodes of data y_values - corresponding y values new_nodes - new x coordinates optional - ends - type of spline, default to 'natural' Output: yprime - apprxoimated derivative """ if ends == "true_vals": D = ode.diffmat(x_nodes, num_nodes=5) yprime_true = np.matmul(D, y_values) ends = [yprime_true[0], yprime_true[-1]] return splineder(x_nodes, y_values, new_nodes, ends=ends) mvals = compute_mvalues(x_nodes, y_values, ends=ends) hvals = x_nodes[1:] - x_nodes[:-1] [coef1, coef2, coef3] = compute_spline_coefs(mvals, hvals, y_values, ends=ends) # changes for second derivative coef1 *= 3 coef2 *= 2 yprime = np.zeros(len(new_nodes)) xsel = x_nodes[1:] ysel = y_values[1:] for j in range(len(new_nodes)): cur = new_nodes[j] index = (cur >= x_nodes[:-1]).astype(int) + (cur < x_nodes[1:]).astype(int) > 1 if (sum(index.astype(int))) == 0: index = -1 yprime[j] = coef1[index] * np.power(cur - xsel[index], 2) + \ coef2[index] * (cur - xsel[index]) + \ coef3[index] return yprime def splineder2(x_nodes, y_values, new_nodes, ends="natural"): """ Compute the second derivative of a function using its cubic spline Input: x_nodes - x nodes of data y_values - corresponding y values new_nodes - new x coordinates optional - ends - tyep of spline, default to 'natural' Output: yprime2 - approximated second derivative """ if ends == "true_vals": D = ode.diffmat(x_nodes, num_nodes=5) yprime_true = np.matmul(D, y_values) ends = [yprime_true[0], yprime_true[-1]] return splineder2(x_nodes, y_values, new_nodes, ends=ends) mvals = compute_mvalues(x_nodes, y_values, ends=ends) hvals = x_nodes[1:] - x_nodes[:-1] [coef1, coef2, coef3] = compute_spline_coefs(mvals, hvals, y_values, ends=ends) # changes for second derivative coef1 *= 6 coef2 *= 2 yprime2 = np.zeros(len(new_nodes)) xsel = x_nodes[1:] ysel = y_values[1:] for j in range(len(new_nodes)): cur = new_nodes[j] index = (cur >= x_nodes[:-1]).astype(int) + (cur < x_nodes[1:]).astype(int) > 1 if (sum(index.astype(int))) == 0: index = -1 yprime2[j] = coef1[index] * (cur - xsel[index]) + coef2[index] return yprime2 n = 11 x_eq = 4 * np.linspace(-1, 1, n) theta = np.linspace(0, np.pi, n) x_cheb = 4 * -np.cos(theta) #x = np.linspace(-1, 1, 10) fun = lambda x: np.exp(-np.power(x, 2)) y_eq = fun(x_eq) y_cheb = fun(x_cheb) x_new = 4 * np.linspace(-1, 1, 1000) y_eq_new = polyinterp(x_eq, y_eq, x_new) y_cheb_new = polyinterp(x_cheb, y_cheb, x_new) y_true = fun(x_new) eq_error = np.abs(y_eq_new - y_true) cheb_error = np.abs(y_cheb_new - y_true) plt.figure() plt.plot(x_eq, y_eq, 'o-', label='eq') plt.plot(x_cheb, y_cheb, 'd-', label='cheb') plt.xlabel('x') plt.ylabel('y') plt.legend() plt.show() plt.figure() plt.plot(x_new, y_eq_new, label="eq spline") plt.plot(x_new, y_cheb_new, label="cheb spline") plt.xlabel('x') plt.ylabel('y') plt.legend() plt.show() plt.figure() #plt.plot(x_new, eq_error, label="eq spline") plt.plot(x_new, cheb_error, label="cheb spline") plt.xlabel('x') plt.ylabel('y') plt.legend() plt.show() theta = np.linspace(0, np.pi, 201) x_trial = 4 * -np.cos(theta) y_trial = polyinterp(x_cheb, y_cheb, x_trial) x_final = np.linspace(-4, 4, 10000) y_final = cubespline(x_trial, y_trial, x_final) y_final = cubespline(x_eq, y_eq, x_final) plt.figure() plt.plot(x_cheb, y_cheb, 'o-') plt.plot(x_final, y_final) plt.show() y_true = fun(x_final) error = np.abs(y_true - y_final) plt.figure() plt.plot(x_final, error) plt.show()
9c81edb53d741621243d63863d055c97de8a0ced
adamrajcarless/python-coding
/codewars-kata08-6KYU-create-phone-number.py
744
4.09375
4
# Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. # Example: # create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890" # The returned format must be correct in order to complete this challenge. # Don't forget the space after the closing parentheses! create_phone_number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def phone_number(s): string = '' for i in s: string += str(i) result = "(" + string[0:3] + ")" + " " + string[3:6] + "-" + string[6:9] + string[10] return result print(phone_number(create_phone_number)) # codewars doesn't accept it, not entirely sure why given it meets the output criteria
7ee1a975421e976dc3827527273f0cc1127f61b8
ParkerMactavish/QuadCopterUI
/src/DataAccess.py
713
3.84375
4
import os ''' open_File requires two parameters -fileName for target file name -mode for reading or writing[read, write] open_File returns a dictionary of values -"FileExist" for whether the target file exists[True, False] -"File" for the file object -"Mode" for the mode of the file object["read", "write"] ''' def open_File(fileName, mode): if os.path.isfile(fileName)==False: file=open(fileName, "w") return {"FileExist":False, "File":file, "Mode":"write"} elif mode=="write": file=open(fileName, "w") return {"FileExist":True, "File":file, "Mode":"write"} elif mode=="read": file=open(fileName, "r") return {"FileExist":True, "File":file, "Mode":"read"} print(os.path.isfile(fileName))
0244f6450cab2d83bb15cbbfad7b17478940cd2b
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Tianx/Lesson3/mailroom.py
5,177
3.8125
4
# ------------------------------------------# # !/usr/bin/env python3 # Title: mailroom.py # Desc: Assignment 1 # Tian Xie, 2020-04-10, Created File # ------------------------------------------# # A dictionary of donor paired with a list of donation amounts dict_of_donors = {'Jeff Bezos': [1.00, 50.00], 'Warren Buffet': [100.00, 1000.00], 'Bill Gates': [100.00, 500.00], 'Tim Cook': [300.00], 'Jack Ma': [2000.00]} # Main Prompt main_prompt = "\n".join(("======= Main Menu ======= \n", "Welcome to the Mailroom. Please select an option:", "1: Send a Thank You", "2: Create a Report", "3: Exit", ">>> ")) def menu_selection(prompt, dispatch_dict): """Displays a menu of choices to the user Args: prompt: main menu dispatch_dict: choices for user to choose from Returns: None. """ while True: response = input(prompt) # continuously collect user selection while True: try: int(response) break except ValueError: response = input('Error: Please enter a number. Please select again >').strip() if dispatch_dict[response]() == "Exit Menu": break def show_donor_list(donor_list): """Displays current donor list. Args: donor_list: 2D data structure (dictionary of objects). Returns: None. """ print('======= The Donor List: =======') print('Donor Name:\n') for i in donor_list: print(i) print('======================================') def adding_donor_info(name, donation, donor_list): """Adding donor info to the list. Args: name: donor name donation: donation amount donor_list: 2D data structure (dictionary of objects). Returns: None. """ if name not in donor_list: added_donor = {name: [donation]} donor_list.update(added_donor) else: donor_list[name].insert(0, donation) # If donor name exists, insert the donation amount rather than updating the dictionary def send_thank_you(): """Sending a thank you email using user input. Args: None Returns: None """ # Ask user for a donor's name or to display current list of donors, then ask for donation amount print() while True: donor_name = input('======= The Thank you Menu: =======\n' "Enter 'list' for to see the list of donors\n" "or enter full name of donor \n" "Enter 'exit' to return to the main menu >") if donor_name not in dict_of_donors and donor_name != "list" and donor_name != "exit": print('\"{}\" is not a current donor, adding to the list...'.format(donor_name)) response = input('Please enter a donation amount for ' + donor_name + ' >') donation_amount = float(response) # Convert the amount into a number adding_donor_info(donor_name, donation_amount, dict_of_donors) create_email(donor_name, donation_amount) elif donor_name == "list": #If the user types list show them a list of the donor names and re-prompt. show_donor_list(dict_of_donors) elif donor_name == "exit": #If the user types exist return to main menu. break elif donor_name in dict_of_donors: #If user enters exsiting donor response = input('Please enter a donation amount for ' + donor_name + ' >') donation_amount = float(response) adding_donor_info(donor_name, donation_amount, dict_of_donors) create_email(donor_name, donation_amount) break def create_email(name, donation): print('=======Email Template=======') print(f'Dear {name},\n\nThank you for your generousity, your donation of ${donation:.2f} will be put to good use.\n\n' 'Warm regards,\nMailroom Staff') def create_report(): """Formating a report. Args: None Returns: None """ print('Donor Name | Total Given | Num Gifts | Average Gift') print('------------------------------------------------------------------') for name in dict_of_donors: total_given = sum(dict_of_donors[name]) number_gifts = len(dict_of_donors[name]) avg = total_given / number_gifts print(f'{name:26} ${total_given:>11.2f} {number_gifts:>11.0f} ${avg:>12.2f}') print('------------------------------------------------------------------') def quit(): print("Exiting the menu now") return "Exit Menu" main_dispatch = {"1": send_thank_you, '2': create_report, '3': quit, } if __name__ == '__main__': menu_selection(main_prompt, main_dispatch)
24f5ef59596ffc07dd1425129fdaed71907b41cb
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/lisa_ferrier/lesson08/test_circle.py
3,036
3.578125
4
#!/usr/bin/env python # test_circle.py # L Ferrier # Python 201, Assignment 08 import pytest from circle import* ######## # step 1 ######## def test_circle(): c = Circle(4) s = Sphere(4) # print(c.radius) assert c.radius == 4 assert s.radius == 4 ######## # step 2 ######## def test_diameter(): c = Circle(4) s = Sphere(8) print(c.diameter, s.diameter) assert c.diameter == 8 assert s.diameter == 16 ######## # step 3 ######## def test_diameter_setter(): c = Circle(4) c.diameter = 2 print(c.radius, c.diameter) assert c.diameter == 2 assert c.radius == 1 s = Sphere(4) s.diameter = 2 assert s.diameter == 2 assert s.radius == 1 ######## # step 4 ######## def test_area(): c = Circle(2) s = Sphere(2) assert c.area == 12.566370614359172 assert s.area == 50.26548245743669 ######## # step 5 ######## def test_from_diameter(): c = Circle.from_diameter(8) print(c.diameter) assert c.radius == 4 s = Sphere.from_diameter(8) print (s.diameter) assert s.radius == 4 ######## # step 6 ######## def test_str(): c = Circle(4) s = Sphere(5) print(str(c)) assert str(c) == 'Circle with radius: 4' assert str(s) == 'Sphere with radius: 5' def test_repr(): c = Circle(4) s = Sphere(5) print(repr(c)) assert repr(c) == 'Circle(4)' assert repr(s) == 'Sphere(5)' ######## # step 7 ######## def test_add(): c1 = Circle(2) c2 = Circle(4) # print(repr(c1 + c2)) assert repr(c1 + c2) == 'Circle(6)' assert repr(Circle(3) + c2) == 'Circle(7)' s1 = Sphere(2) s2 = Sphere(4) assert repr(s1 + s2) == 'Sphere(6)' assert repr(Sphere(3) + s2) == 'Sphere(7)' def test_mul(): c1 = Circle(2) c2 = Circle(4) assert repr(c1 * 3) == 'Circle(6)' assert repr(3 * c2) == 'Circle(12)' def test_div(): c1 = Circle(4) s1 = Sphere(4) assert repr(c1 // 2) == 'Circle(2)' assert repr(s1 // 2) == 'Sphere(2)' # check to make sure floats are rounded to nearest int assert repr(c1 // 3) == 'Circle(1)' assert repr(s1 // 3) == 'Sphere(1)' ######## # step 8 ######## def test_compare(): c1 = Circle(2) c2 = Circle(3) c3 = Circle(4) c4 = Circle(3) assert c1 < c4 assert c2 > c1 assert c1 == c4 assert c3 != c4 s1 = Sphere(2) s2 = Sphere(3) s3 = Sphere(4) s4 = Sphere(3) assert s1 < s4 assert s2 > s1 assert s1 == s4 assert s3 != s4 def test_sort_circles(): circles = [Circle(6), Circle(7), Circle(8), Circle(4), Circle(0), Circle(2), Circle(3), Circle(5), Circle(9), Circle(1)] circles.sort() assert circles == [Circle(0), Circle(1), Circle(2), Circle(3), Circle(4), Circle(5), Circle(6), Circle(7), Circle(8), Circle(9)] ############################ # step 8 - optional features ############################ def test_reflection(): c1 = Circle(4) assert c1 * 3 == 3 * c1 s1 = Sphere(4) assert s1 * 3 == 3 * s1
658c83e0f9386126a866fb7f507528f89352d59f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/allen_maxwell/Lesson_08/circle.py
5,215
3.9375
4
#!/usr/bin/env python3 # Allen Maxwell # Python 210 # 1/4/2020 # circle.py # ver 2 import math def is_valid_entry(value): if isinstance(value, str): raise ValueError('Value must be a number') elif isinstance(value, (int, float)): if value < 0: raise ValueError('Value must be a positive number') else: return True else: return False def is_valid_for_div(denominator): if is_valid_entry(denominator): if denominator == 0: raise ValueError('Denominator value must greater than zero') else: return True else: if denominator.radius == 0: raise ValueError('Denominator value must greater than zero') else: return False def is_valid_for_add(self, value): if isinstance(value, str): raise ValueError('Value must be a number') elif isinstance(value, (int, float)): if self.radius + value < 0: raise ValueError('Value must less than or equal to the radius') else: return True else: return False def is_valid_for_sub(self, value): if isinstance(value, str): raise ValueError('Value must be a number') elif isinstance(value, (int, float)): if self.radius - value < 0: raise ValueError('Value must less than or equal to the radius') else: return True else: if self.radius - value.radius < 0: raise ValueError('Value must less than or equal to the radius') else: return False class Circle(object): def __init__(self, radius=0): if is_valid_entry(radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, radius): if is_valid_entry(radius): self._radius = radius @property def diameter(self): return self._radius * 2 @diameter.setter def diameter(self, diameter): if is_valid_entry(diameter): self._radius = diameter / 2 @property def area(self): return math.pi * self._radius * 2 @area.setter def area(self, area): raise AttributeError('Area cannot be set') @classmethod def from_diameter(cls, diameter): if is_valid_entry(diameter): return cls(diameter / 2) def __str__(self): return 'Circle with radius: {}'.format(self._radius) def __repr__(self): return 'Circle({})'.format(self._radius) def __add__(self, other): if is_valid_for_add(self, other): return self.__class__(self._radius + other) else: return self.__class__(self._radius + other.radius) def __radd__(self, other): if is_valid_for_add(self, other): return self.__class__(self._radius + other) else: return self.__class__(self._radius + other.radius) def __iadd__(self, other): if is_valid_for_add(self, other): return self.__class__(self._radius + other) else: return self.__class__(self._radius + other.radius) def __sub__(self, other): if is_valid_for_sub(self, other): return self.__class__(self._radius - other) else: return self.__class__(self._radius - other.radius) def __isub__(self, other): if is_valid_for_sub(self, other): return self.__class__(self._radius - other) else: return self.__class__(self._radius - other.radius) def __mul__(self, other): if is_valid_entry(other): return self.__class__(self._radius * other) else: return self.__class__(self._radius * other.radius) def __rmul__(self, other): if is_valid_entry(other): return self.__class__(self._radius * other) else: return self.__class__(self._radius * other.radius) def __imul__(self, other): if is_valid_entry(other): return self.__class__(self._radius * other) else: return self.__class__(self._radius * other.radius) def __truediv__(self, other): if is_valid_for_div(other): return self.__class__(self._radius / other) else: return self.__class__(self._radius / other.radius) def __idiv__(self, other): if is_valid_for_div(other): return self.__class__(self._radius / other) else: return self.__class__(self._radius / other.radius) def __eq__(self, other): return self.radius == other.radius def __lt__(self, other): return self.radius < other.radius def __gt__(self, other): return self.radius > other.radius def sort_key(self): return self.radius class Sphere(Circle): def __str__(self): return 'Sphere with radius: {}'.format(self._radius) def __repr__(self): return 'Sphere({})'.format(self._radius) @property def volume(self): return (4/3) * math.pi * self.radius ** 3 @property def area(self): return 4 * math.pi * self.radius ** 2
abb1c338ea69227d8e257f6a3a5de62e54b5d06c
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/barb_matthews/lesson2/series.py
1,809
4.28125
4
## Lesson 2, Exercise 2.4 Fibonnaci Series ## By: B. Matthews ## 9/11/2020 def fibonacci(n): #"""Generates a Fibonnaci series with length n""" if (n == 0): return 0 elif (n == 1): return 1 else: return fibonacci(n-1) + fibonacci(n-2) def lucas(n): #"""Generates a Lucas series with length n""" if (n == 0): return 2 elif (n == 1): return 1 else: return lucas(n-1) + lucas(n-2) def sum_series (n, a=0, b=1): #"""Generates a series with first two numbers that user specifies""" if (n == 0): return a elif (n == 1): return b else: return sum_series(n-1, a, b) + sum_series(n-2, a, b) ##Test the function #n = int(input("Enter a number >> ")) #for i in range (n+1): #print (lucas(i)) #print ("Fibonacci:", n,"th value is: ", fibonacci(n))# #print ("Lucas series: ", lucas(n)) ##Test using the assert template if __name__ == "__main__": # run some tests assert fibonacci(0) == 0 assert fibonacci(1) == 1 assert fibonacci(2) == 1 assert fibonacci(3) == 2 assert fibonacci(4) == 3 assert fibonacci(5) == 5 assert fibonacci(6) == 8 assert fibonacci(7) == 13 assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(4) == 7 # test that sum_series matches fibonacci assert sum_series(5) == fibonacci(5) assert sum_series(7, 0, 1) == fibonacci(7) # test if sum_series matched lucas assert sum_series(5, 2, 1) == lucas(5) # test if sum_series works for arbitrary initial values assert sum_series(0, 3, 2) == 3 assert sum_series(1, 3, 2) == 2 assert sum_series(2, 3, 2) == 5 assert sum_series(3, 3, 2) == 7 assert sum_series(4, 3, 2) == 12 assert sum_series(5, 3, 2) == 19 print("Tests passed!")
881a0180c255d7a7c771b1261bbaf31272bc04ee
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/steve-long/lesson04-dicts-sets-files/ex-4-4-file-io/copy_file_binary.py
11,848
3.890625
4
#!/usr/bin/env python3 # ============================================================================== # Python210 | Fall 2020 # ------------------------------------------------------------------------------ # Lesson04 # File Exercise (copy_file_binary.py) # Steve Long 2020-10-14 | v0 # # Requirements: # ============= # # [1] Write a program which copies a file from a source, to a destination # (without using shutil, or the OS copy command (you are essentially # writing a simple version of the OS copy command)). # # [2] This should work for any kind of file, so you need to open the files in # binary mode: open(filename, 'rb') (or 'wb' for writing). Note that for # binary files, you can’t use readline() – lines don’t have any meaning for # binary files. # # [3] Test it with both [a] text and [b] binary files (maybe a jpeg or # something of your choosing). # # [4] Advanced: make it work for any size file: i.e. don’t read the entire # contents of the file into memory at once. This should only be a few lines # of code :-) # # Implementation: # --------------- # # The implementation is much larger than is actually required, but as implied # in requirement [4] the section of code that actually performs the # read/write op is only 8 lines (and that many because of PEP8 "neatness" # requirements.) # # [1] Function copy_file_binary # [2] Context read/write ops with 'rb'/'wb' option. # [3] Multiple use-cases. See functional test ft_copy_file_binary. # [4] Implemented using buffered i/o and optional read size argument. # # Function names, variables, block comments, line continuation, and # operator spacing per PEP8 guidelines. Checked with flake8. # # Dependencies: # ------------- # # Source data folder "source/" containing the following documents (files): # # robot.jpg # samaritaine.jpg # widgets.txt # # Target data folder "target/" for copying documents (files) to. # # Script Usage: # ------------- # # ./copy_file_binary.py executes functional test ft_copy_file_binary which # verifies requirement[3] and verifies function arguments. # # Issues: # ------- # # Requirement [4] was a little ambiguous. # # History: # -------- # 000/2020-10-12/sal/Created. # ============================================================================= import pathlib def copy_file_binary(source_pathname, target_pathname, allow_overwrite=False, chunk_size=2048): """ copy_file_binary(<source_pathname>, <target_pathname>, <allow_overwrite>, <chunk_size>) ------------------------------------------------------------------- Copy a source file to a destination, optionally overwriting an existing file with the same name. Satisfies requirement [1]. Entry: <source_pathname> ::= (str) A valid source file absolute path string. <target_pathname> ::= (str) A valid target file absolute path string. <allow_overwrite> ::= (bool) When True, allow replacement of an existing file at <target_pathname>. Default is False. <chunk_size> ::= (int) Number of bytes to read from source file at read interval. Must be greater than zero and multiple of 64. Default is 2048. Exit: Returns True if successful, False otherwise. For issues related to arguments, raises standard Exception with custom message. Raises: ValueError, FileExistsError, FileNotFoundError, PermissionError """ success = False # # Begin argument quality assurance. # message = "" if (len(source_pathname) > 0): source_path = pathlib.Path(source_pathname) if (source_path.exists()): if (len(target_pathname) > 0): target_path = pathlib.Path(target_pathname) if (target_path.exists()): if (allow_overwrite): if ((chunk_size > 0) and ((chunk_size % 64) == 0)): pass else: message \ = "Arg chunk_size must be > 0, multiple of 64" raise ValueError(message) else: message = "Overwrite of file {} not allowed" \ .format(target_pathname) raise FileExistsError(message) else: pass else: message = "Arg target_pathname is blank" raise ValueError(message) else: message = "File {} is missing".format(source_pathname) raise FileNotFoundError(message) else: message = "Arg source_pathname is blank" raise ValueError(message) # # End argument quality assurance. # # The principal functionality. Satisfies requirement [2] and [4]. # Even without the explicit chunk_size, this technique will still read # entire binary files well into the gigabyte range. # try: with open(source_pathname, 'rb') as source_file, \ open(target_pathname, 'wb') as target_file: while True: chunk = source_file.read(chunk_size) if (not chunk): break else: target_file.write(chunk) except PermissionError as pex: success = False raise pex else: success = True return success def remove_file_no_error(pathname): """ Remove a file (document) on the specified pathname. """ result = False path = pathlib.Path(pathname) if (path.exists()): try: path.unlink() except FileNotFoundError: pass finally: result = (not path.exists()) return result def create_file_no_error(pathname): """ Create a file (document) on the specified pathname. """ result = False path = pathlib.Path(pathname) if (path.exists()): result = True else: f = open(pathname, "w+") f.close() result = path.exists() return result def ft_copy_file_binary(): """ Test function copy_file_binary with a set of use-cases, printing the result for each and summarizing the results with a PASSED or FAILED message. """ # # Define real and imaginary input and output paths. # valid_base_name\ = str(pathlib.Path.cwd()) imaginary_base_path_name\ = "{}/{}".format(str(pathlib.Path.cwd().parent), "imaginary") existing_source_pathname\ = "{}/{}".format(valid_base_name, "source/widgets.txt") new_target_pathname\ = "{}/{}".format(valid_base_name, "target/frammitz.txt") remove_file_no_error(new_target_pathname) existing_target_pathname\ = "{}/{}".format(valid_base_name, "target/widgets.txt") create_file_no_error(existing_target_pathname) imaginary_source_pathname\ = "{}/{}".format(imaginary_base_path_name, "source/widgets.txt") imaginary_target_pathname\ = "{}/{}".format(imaginary_base_path_name, "target/widgets.txt") invalid_pathname = "" small_bin_source_pathname\ = "{}/{}".format(valid_base_name, "source/robot.jpg") small_bin_target_pathname\ = "{}/{}".format(valid_base_name, "target/robot.jpg") remove_file_no_error(small_bin_target_pathname) # NOTE: Originally run with movie file "Gravity.mv4" because this was the # biggest file available (3.22 GB). DRM rules and Git repository # limitations prevent this from being included with the final solution. # Instead, a photo of a building in Paris was substituted. # large_bin_source_pathname\ # = "{}/{}".format(valid_base_name, "source/Gravity (HD).m4v") # large_bin_target_pathname\ # = "{}/{}".format(valid_base_name, "target/Gravity (HD).m4v") large_bin_source_pathname\ = "{}/{}".format(valid_base_name, "source/samaritaine.jpg") large_bin_target_pathname\ = "{}/{}".format(valid_base_name, "target/samaritaine.jpg") remove_file_no_error(large_bin_target_pathname) # # Construct use-cases defined by test parameter lists consisting of # use-case#, list of input arguments, and expected output from function. # use_case = [[]]*10 # # Satisfies: requirement [3a] # use_case[0] =\ ["1", "Copy existing text file to new file", [existing_source_pathname, new_target_pathname, True, 2048], True ] use_case[1] =\ ["2", "Copy existing text file to existing file, allowing overwrite", [existing_source_pathname, existing_target_pathname, True, 2048], True ] use_case[2] =\ ["3", "Copy existing text file to existing file, disallowing overwrite", [existing_source_pathname, existing_target_pathname, False, 2048], False ] use_case[3] =\ ["4", "Copy existing text file to non-existent directory", [existing_source_pathname, imaginary_target_pathname, True, 2048], False ] use_case[4] =\ ["5", "Copy non-existent text file to non-existent directory", [imaginary_source_pathname, imaginary_target_pathname, True, 2048], False ] use_case[5] =\ ["6", "Copy non-existent text file to invalid file", [imaginary_source_pathname, invalid_pathname, True, 2048], False ] use_case[6] =\ ["7", "Copy invalid text file to non-existent file", [invalid_pathname, imaginary_target_pathname, True, 2048], False ] # # Satisfies: requirement [3b] # use_case[7] =\ ["8", "Copy small binary file (95 KB)", [small_bin_source_pathname, small_bin_target_pathname, True, 2048], True ] # # Satisfies: requirement [4] # use_case[8] =\ ["9", "Copy large binary file (2.5 MG to 3.22 GB)", [large_bin_source_pathname, large_bin_target_pathname, True, 2048], True ] use_case[9] =\ ["10", "Invalid chunk size", [small_bin_source_pathname, small_bin_target_pathname, True, 5001], False ] # # Execute list of functional tests. # success = True msg = "" for uc in use_case: uc_index = uc[0] uc_descr = uc[1] uc_args = uc[2] uc_src = uc_args[0] uc_tgt = uc_args[1] uc_aovd = uc_args[2] uc_chksz = uc_args[3] uc_expected = uc[3] uc_actual = False try: uc_actual = False uc_actual = copy_file_binary(uc_src, uc_tgt, uc_aovd, uc_chksz) msg = "" except (ValueError, FileExistsError, FileNotFoundError, PermissionError) as excptn: msg = str(excptn) finally: ok = ((uc_actual == uc_expected) or (uc_actual is None)) msg = "Use Case {}: {}\n {}{}"\ .format(uc_index, uc_descr, ("OK" if ok else "FAILED"), (f": {msg}" if (len(msg) > 0) else "")) print(msg) success = success and ok return "Functional test for copy_file_binary: {}"\ .format(("PASSED" if success else "FAILED")) if __name__ == "__main__": print(ft_copy_file_binary())
88c8c3cf010401484e6d10955296b929aa464671
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Steven/lesson06/mailroom04.py
4,366
3.65625
4
#! bin/user/env python3 import sys from operator import itemgetter """ Program Part4: Add a full suite of unit tests: “Full suite” means all the code is tested. In practice, it’s very hard to test the user interaction, but you can test everything else. Therefore you should make sure that there is as little logic and untested code in the user interaction portion of the program as possible. """ # Donor name, donation amount, donation history donor_list = { "John Doe": [2000, 2], "Jane Doe": [3000, 3], "George Washington": [1, 1], "Andrew Jackson": [20, 2], "Benjamin Franklin": [100, 3] } # Main options menu for user to pick from def main(): while True: options() # Display each option to the user try: choice = int(input("What would you like to do? ")) # Using a dictionary for as a switch case switch_func_dict = { 1: thank_you, 2: get_report, 3: all_letters, 4: quit } switch_func_dict.get(choice)() except ValueError as error_message: print(error_message) except TypeError: print("Not a valid option, please select again.") # Menu of options for the user in the script def options(): print("You have 4 options to choose from: ", "\n" "1) Send Thank you", "\n" "2) Create Report", "\n" "3) Send a Thank you note to all donors", "\n" "4) Exit", "\n" ) # Ask for a donor name and donation amount, send an email to that donor once completed def thank_you(): name = input("Enter a first and last name (type 'list' to see existing donors): ").title() if name.lower() == "list": print(donor_list) thank_you() try: gift = float(input("Enter a donation amount: ")) except ValueError as error_message: # Catch if the user doesn't input a number print(error_message) update_donor_list(name, gift) # Thank you email to the donor print(thank_you_letter(name, gift)) def update_donor_list(name, gift): if name in donor_list.keys(): # check if name is in the dict donor_list[name] = [(donor_list[name][0] + gift), (donor_list[name][1] + 1)] # Use the key to update the values using a list else: # add the new donor and their donation amount with 1 donation history donor_list.update({name: [gift, 1]}) return donor_list def thank_you_letter(name, donation): email = f"Thank you {name} for your generous donation of ${donation:.2f}, your kindness is very appreciated." + "\n" return email def display_report(): for row in get_report(): print(row) # Show a list of current donor's in the list and sorted by total number of donations def get_report(): fields = ["Donor Name", "Total Given", "Num Gifts", "Average Gift"] # report headers report_list = [] # temp list used later in order to sort by number of total gifts # format headers to have a uniform look print(f"{fields[0]:<20} | {fields[1]:<11} | {fields[2]:<3} | {fields[3]}") # line break for report print("{}".format('-' * 61)) for item in donor_list: donation_total = donor_list[item][0] donation_trans = donor_list[item][1] avg_donation = donation_total / donation_trans temp_list = [item, donation_total, donation_trans, avg_donation] # Taking the dictionary copying over to a temp list in order to sort report_list.append(temp_list) sorted_donors = sorted(report_list, key=itemgetter(1), reverse=True) # Sorting list based on the total donation for each donor for donor in sorted_donors: print(f"{donor[0]:<20} $ {donor[1]:>11.2f} {donor[2]:>11} $ {donor[3]:>11.2f}") return sorted_donors # Create a text file using the name of the donor for each file name def all_letters(): for name in donor_list: with open(f"thank_you_{name.lower()}.txt", 'w') as fh: fh.write(f"Dear {name.title()},\nThank you for your very generous donation of ${(donor_list[name.title()][0]):.2f}." \ f"Your help will go a long way in supporting our foundation." \ f"\n\nThank you,\nYour Non-Profit Team\n\n") def quit(): print("Closing script") sys.exit() if __name__ == "__main__": print("Mailroom script has been started. ") main()
f06effa5e022502aa270993a58db4e80114fd674
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mimalvarez_pintor/lesson03/list_lab.py
1,131
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 26 20:35:32 2020 @author: miriam """ # Series 1 L = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(L) F = input("Please type in a fruit: ") L.append(F) print(L) for num in L: num = int(input("\nPlease enter in a fruit number (1-5): ")) print(num, L[num-1]) break else: print('') L = ["Grapes"] + L print(L) L.insert(0, "Bananas") print(L) for fruits in L: if fruits.startswith('P'): print(fruits) # Series 2 print(L) L2 = L del L2[-1] print(L2) D = input('Which fruit should be deleted: ') if D in L2: L2.remove(D) else: print(D, "not in list") print(L2) # Series 3 def series3(L): L3 = L[:] for i in L3: Q = input("Do you like {}: ".format(i.lower())) while Q.lower() != "yes" and Q.lower() != "no": Q = input("Do you like {}: ".format(i.lower())) if Q.lower() == "no": L.remove(i) else: continue print(L, "\n") # series 4 def series4(L): L4 = [] for i in L: L4.append(i[::-1]) L.pop() print (L4) print (L)
f93b924c0308a6a61d1bc5133158c89e4869620a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/IanMayther/Lesson08/circle_class.py
1,706
4
4
#!/usr/bin/env python3 import math class Circle: """ A class-based system for rendering a circle. """ def __init__(self, rad=None): if rad is None: raise AttributeError else: self.radius = rad def __str__(self): return f'{self.__class__.__name__} with radius: {self.radius:.4f}' def __repr__(self): return f'{self.__class__.__name__}({self.radius})' def __add__(self, other_circle): total = self.radius + other_circle.radius return Circle(total) def __eq__(self, other_circle): return self.radius == other_circle.radius def __mul__(self, other_circle): if isinstance(other_circle, int): prod = self.radius * other_circle else: prod = self.radius * other_circle.radius return Circle(prod) def __rmul__(self, value): return self.__mul__(value) def __lt__(self, other_circle): return self.radius < other_circle.radius @property def diameter(self): 'Calculate diameter of circle' return 2 * self.radius @diameter.setter def diameter(self, val): self.radius = val / 2 @classmethod def from_diameter(cls, dia): cls.diameter = dia cls.radius = dia / 2 return cls @property def area(self): 'Calculates area of circle' return round(math.pi * self.radius ** 2, 5) class Sphere(Circle): """ A class-based system for rendering a sphere. """ @property def volume(self): return (4/3) * math.pi * self.radius ** 3 @property def area(self): return 4 * math.pi * self.radius ** 2
c10861448bb9d4be90c2405477a4cb6bb407bf95
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/ReemAlqaysi/Lesson09_2/cli_main.py
3,815
3.875
4
#!/usr/bin/env python3 import sys, os from datetime import datetime from donor_models import Donor, DonorCollection # Mailroom functions def prompt_user(): prompt = "\n".join(("Welcome to the MailRoom!", "Please Choose an action:", "1 - Send a Thank You to a single donor.", "2 - Create a Report.", "3 - Send letters to all donors.", "4 - Quit", ">>> ")) response = input(prompt) return response def thank_you_text(): #Ask for donor name while True: donor_name = input("Enter the donor name.'list' to get list of donors, or 'q' to quit) ") if donor_name.lower() == 'q': exit_program() # If user types list print donors elif donor_name.lower() == "list": print('\nCurrent list of donors:\n') print('\n'.join(dc.donor_names)) continue else: if donor_name not in dc.donor_names: answer = input("The donor name is not in the list of donors. " "Do you want to add the donor? Yes or No ") if answer.lower() == "yes": name = donor_name else: exit_program() #Ask for donation amount donation_amount = input("Enter the donation amount (or q to quit) ") if donation_amount.lower() == 'q': exit_program() elif float(donation_amount) > 0: amount = float(donation_amount) dc.update_donor(name,amount) else: print("The number you enter must be greater than 0.") dc.update_donor(name,amount) # Generate & print email to screen, return to main program email = dc.get_donor(name).generate_email() print(email) return def print_formatted_report(report): formatted_report = ['', 'Donor Name | Total Donation | Num Donations | Avg Donation |', '-------------------------------------------------------------------------------'] for donor in report: donor_name, total, number, average = donor formatted_report.append(f'{donor_name:<30} ${total:>14.2f} {number:14d} ${average:>12.2f}') formatted_report.append('') print('\n'.join(formatted_report)) def create_report(): # Generate, format, and print report data report = dc.generate_report_data() print_formatted_report(report) def letter_to_all(): #send letter to all donors in the current directory for name in dc.donor_names: filename = name.replace(' ', '_').replace(',', '') + ".txt" filename = filename.lower() filetext = dc.get_donor(name).generate_email() with open(filename,'w+') as output: output.write(filetext) print("\nLetters {} have been printed and are saved in the current directory".format(filename)) def exit_program(): #exit the program print('Goodbye') os.sys.exit() def main(): options = { '1': thank_you_text, '2': create_report, '3': letter_to_all, '4': exit_program } while True: #if response in options: try: response = prompt_user() options[response]() except KeyError: print("\n'{}' is not a valid answer, please select option from 1-4 !. \n >> ".format(response)) if __name__ == "__main__": # Create some donor data for running the program from the command line dc = DonorCollection() donors = ['Charlie Puth', 'Demi Lovato', 'Meghanr Tainor'] amounts = [[50.00,25.00,100.00], [100.00,50.00,80.00], [200.00,100.00,300.00]] for donor, amount in zip(donors,amounts): for donation in amount: dc.update_donor(donor, donation) # Driver for main function main()
919274fb66cad43bd13214839b8bc7cd8b2ba625
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Steven/lesson08/circle_class.py
2,445
4.5
4
#!/usr/bin/env python3 """ The goal is to create a class that represents a simple circle. A Circle can be defined by either specifying the radius or the diameter, and the user can query the circle for either its radius or diameter. Other abilities of a Circle instance: Compute the circle’s area. Print the circle and get something nice. Be able to add two circles together. Be able to compare two circles to see which is bigger. Be able to compare to see if they are are equal. (follows from above) be able to put them in a list and sort them. """ import math class Circle(): # Circle object with a given radius def __init__(self, radius): self.radius = radius @property def get_diameter(self): return self.radius * 2 @get_diameter.setter def get_diameter(self, value): self.radius = value / 2 @property def get_area(self): return math.pi * self.radius ** 2 @get_area.setter def get_area(self, value): raise AttributeError @classmethod def from_diameter(cls, value): return cls(value / 2) # For printing out def __str__(self): return f"Circle with a radius of: {self.radius}, Diameter of: {self.get_diameter}" def __repr__(self): return f"Circle({self.radius})" # Numeric protocols def __add__(self, other): return Circle(self.radius + other.radius) def __mul__(self, other): return Circle(self.radius * other) def __lt__(self, other): return self.radius < other.radius def __le__(self, other): return self.radius <= other.radius def __gt__(self, other): return self.radius > other.radius def __ge__(self, other): return self.radius >= other.radius def __ne__(self, other): return self.radius != other.radius def __eq__(self, other): return self.radius == other.radius class Sphere(Circle): # Override the Circle str method def __str__(self): return f"Sphere with a radius of: {self.radius}, Diameter of: {self.get_diameter}" # Override the Circle repr method def __repr__(self): return f"Sphere({self.radius})" @property def volume(self): return (4 / 3) * math.pi * self.radius ** 3 # Formula for volume of a sphere @property def get_area(self): return 4 * math.pi * self.radius ** 2 # Formula for the surface area of a sphere
05ad62f4a837bab29deb96c360e27ffd88cdd361
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/tihsle/lesson09/mailroom_oo/cli_main.py
1,669
3.796875
4
#!/usr/bin/env python3 from donor_models import Donor, DonorCollection import sys def select_donor(donors): #select the donor for the thank you email while True: answer = input("Which donor to send Thank You to?\n" "(Type 'list' to show list of donors)\n").title() if answer.lower() == "list": print(donors.list_donors()) else: break return answer def send_thank_you(donors): #send a thank you #which donor patron_name = select_donor(donors) #exception handling for user input loop = True while loop: donation = input("How much is the gift?\n") try: patron_gift = float(donation) break except ValueError: print("\nNot a good value!\n") donors.add_donor(patron_name, patron_gift) print(Donor(patron_name, donation).send_thank_you()) def create_report(donors): print(donors.report()) def quit(donors): #quit the program sys.exit() def main(): donors = DonorCollection() #generate the menu menu = "\n".join((">", "Please choose from the following:", "1 - Send a Thank You to a single donor", "2 - Create a Report", "3 - Quit", "> ")) selections = {"1": send_thank_you, "2": create_report, "3": quit} while True: ans = input(menu) try: selections.get(ans)(donors) except TypeError: print("Only 1, 2 or 3 is valid!") pass if __name__ == '__main__': main()
4a2a4e2d20d9bb764fac5a93b4732a6461a5d095
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kristoffer_jonson/lesson1/warmup_2_string_match.py
191
3.578125
4
def string_match(a, b): length = len(a) if len(a) > len(b): length = len(b) count = 0 for i in range(length-1): if a[i:i+2] == b[i:i+2]: count = count +1 return count
008d725f18c563997e49a64460611c944120a0eb
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/cjfortu/lesson08/Sparse_Array.py
2,287
3.640625
4
#!/usr/bin/env python class Sparse_Array: """Class for a 1D array which functions as a list, but does not store zero values.""" def __init__(self, values=None): """Store all non-zero list values in a dict, with the indices as keys.""" self.length = len(values) if values is None: self.values = {} else: self.values = {i: value for i, value in enumerate(values) if value != 0} def __len__(self): """ Return the length of the initial input, not the stored dict. The initial input can be updated. """ return self.length def __getitem__(self, query): """Read the input first, then retrieve a value or raise an error.""" if isinstance(query, slice): keys = list(range(self.length))[query] return [self.values[key] if (key in self.values.keys()) else 0 for key in keys] elif isinstance(query, tuple): # For use in 2D arrays. return 'yes tuple' else: if query > self.length: raise IndexError('cannot access index beyond end') else: try: return self.values[query] except KeyError: return 0 def __setitem__(self, query, value): """ Depending on the input, raise an error, store a value, or delete the value & key. The virtual length remains unchanged. """ if query > self.length: raise IndexError('cannot access index beyond end') elif value != 0: self.values[query] = value else: del self.values[query] # Simulates storing a zero def __delitem__(self, query): """Delete a value & key, and shorten the length.""" del self.values[query] self.length -= 1 def __iter__(self): """Make the dict iterable.""" return iter(self.values) def __reversed__(self): """Make the dict reversible.""" return reversed(self.values) def append(self, value): """Make the dict appendible.""" self.values[self.length] = value self.length += 1
496eb5424686f903c2ec4372d8275ee73cd97a32
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/bplanica/lesson04/trigrams.py
4,502
3.984375
4
#!/usr/bin/env python3 import random # ------------------------------ # # Assignment 4 (Trigrams!) for Python 210 # Dev: Breeanna Planica # ChangeLog: (who, when, what) # BPA, 8/18/2019, Created and tested script # BPA, 8/20/2019, added confirmaiton of ebook type # ------------------------------ # # ----- Data ----- # # ---------------- # lst_words = [] # list to store words from txt file lst_story = [] # list to store word sequences using trigrams #file_name = "./sherlock.txt" # text file to read/process # ----- Processing ----- # # ---------------------- # def read_file(obj_file_name): """ reads text file and gathers all words within the story """ try: obj_file = open(obj_file_name, "r") # open file as read only except: print("Text file not found in working folder.") raise SystemExit for row in obj_file: # for each line in the text file... row = row.replace(",", "") # remove commas row = row.replace("(", "") # remove parenthesis row = row.replace(")", "") # remove parenthesis row = row.replace("--", " ") # remove double hyphens words = row.split() # split words by spaces for item in words: lst_words.append(item) # append each word to store all words from txt file return lst_words def read_file_ebook(obj_file_name): """ reads text file and gathers all words within the story """ try: obj_file = open(obj_file_name, "r") # open file as read only except: print("Text file not found in working folder.") raise SystemExit switch = False # detemines start of the story in Project Gutenberg texts for row in obj_file: # for each line in the text file... row = row.replace(",", "") # remove commas row = row.replace("(", "") # remove parenthesis row = row.replace(")", "") # remove parenthesis row = row.replace("--", " ") # remove double hyphens if switch == True: words = row.split() # split words by spaces for item in words: lst_words.append(item) # append each word to store all words from txt file if row[:41] == "*** START OF THIS PROJECT GUTENBERG EBOOK": # detmines start switch = True if row[:39] == "*** END OF THIS PROJECT GUTENBERG EBOOK": # determines the end switch = False return lst_words def build_trigrams(words): """ build up the trigrams dict from the list of words """ trigrams = {} # define/empty dictionary for i in range(len(words) - 2): # for all words in list except last 2 pair = words[i], words[i + 1] # create a tuple from the pair follower = words[i + 2] # trigrams.setdefault(pair, []) # create a key from a pair if not found alreay in existance trigrams[pair].append(follower) # append the follower to the list return trigrams def build_story(dictionary): length = len(dictionary) # find the length of the dictionary start = random.randint(0, length) # select a random location to start pair = list(dictionary.keys())[start] # find the first pair for item in pair: lst_story.append(item) # append to the story follower = random.choice(dictionary[pair]) lst_story.append(follower) try: i = 1 while i < 100: # do this 100 times (to keep the story shorter) follower = random.choice(dictionary[lst_story[-2], lst_story[-1]]) # find the new pair lst_story.append(follower) # append the follower to the story list i += 1 return (lst_story) except: return (lst_story) # if there is an exception(pair/key not found), stop before 100 # ----- Presentation ----- # # ------------------------ # if __name__ == "__main__": response = input("What is the file name you would like to process? (file name and extension only): ").strip() file_name = "./" + response response = input("Is this a full Project Gutenburg eBook? (Y/N): ").strip() print() if response.upper() == "Y": lst_words = read_file_ebook(file_name) # gather the list of words else: lst_words = read_file(file_name) # gather the list of words trigrams = build_trigrams(lst_words) # build the dictionary #for key, value in trigrams.items(): # print(f"{key}, {value}") lst_story = build_story(trigrams) # build the story print(" ".join(lst_story)) # print the list/story with spaces in between words
b302b5c46666bc07835e9d4e115b1b59c0f9e043
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/franjaku/Lesson_2/grid_printer.py
1,311
4.4375
4
#!/Lesson 2 grid printer def print_grid(grid_dimensions=2,cell_size=4): """ Print a square grid. Keyword Arguments grid_dimensions -- number of rows/columns (default=2) cell_size -- size of the cell (default=4) Both of the arguments must be interger values. If a non-integer value is input it will be truncated after the decimal point. For instance: 1.5 -> 1 2.359 -> 2 5.0 -> 5 """ grid_dimensions = int(grid_dimensions) cell_size = int(cell_size) Building_line1 = ('+ ' + '- '*cell_size)*grid_dimensions + '+' Building_line2 = ('| ' + ' '*cell_size)*grid_dimensions + '|' for x in range(grid_dimensions): print(Building_line1) for y in range(cell_size): print(Building_line2) print(Building_line1) return 1 if (__name__ == '__main__'): print('==========================') print('Grid Printer Exercise 1') print('Showing ouput for: print_grid()') print_grid() print('==========================') print('Grid Printer Exercise 2') print('Showing ouput for: print_grid(cell_size=8)') print_grid(cell_size=8) print('==========================') print('Grid Printer Exercise 3') print('Showing ouput for: print_grid(5,3)') print_grid(5,3)
96b3aff4e3e47ee94b5d4adc7dde76438c5f027c
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/calvin_fannin/Lesson09/mailroom_oo/donor_models.py
2,430
3.859375
4
#!/usr/bin/env python3 """ Class to hold a information for one donor first name lastname and donation amount """ class Donor(): def __init__(self, firstname, lastname,donation): self.fname = firstname.title().strip() self.lname = lastname.title().strip() if donation <= 0: donationError = ValueError('Donation cannot be negative') raise donationError else: self.donations = [donation] self.dc = DonorCollection() @property def fullname(self): """ Returns the first and lastname as one string """ return self.fname + " " + self.lname @property def totaldonation(self): """ Returns the sum of all donations for a donor """ return sum(self.donations) def add_donation(self,donation): """ Returns the sum of all donations for a donor """ if donation < 0: donationError = ValueError('Donation cannot be negative') raise donationError else: self.donations.append(donation) class DonorCollection(): """ Class to hold a collection of donor objects """ def __init__(self, donor=None): if donor is None: self.donors = [] else: self.donors = donor def add_donor(self, donor): self.donors.append(donor) def list_donors(self): return self.donors def add_donation(self, donor_name, amount): #add to the donation list of lists when donor exists for i, donor in enumerate(self.donors): if donor.fullname.lower() == donor_name.lower(): self.donors[i].donations.append(amount) def search_fullname(self, donor_name): #search to see if donor already exits for donor in self.donors: if donor.fullname.lower().strip() == donor_name.lower().strip(): return True return False def create_summary(self): """ Returns a list of donation summaries for each donor """ summary_values =[] for donor in self.donors: #aggregate dontations and get averages donor_name = donor.fullname total = sum(donor.donations) donate_count = len(donor.donations) donate_avg = total / donate_count summary_values.append([donor_name, total, donate_count, donate_avg]) return summary_values
a89dce9f76910fbacb0cfbe8b2ffab5b861a85bd
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/cbrown/Lesson 2/grid_printer.py
577
4.25
4
#Grid Printer Excercise Lesson 2 def print_grid(x,y): ''' Prints grid with x blocks, and y units for each box ''' #get shapes plus = '+' minus = '-' bar = '|' #minus sign sequence minus_sequence = y * minus grid_line = plus + minus_sequence #Create bar pattern bar_sequence = bar + ' ' * y #Print out Grid for i in range(x): print(grid_line * x, end = plus) for i in range(y): print('\n',bar_sequence * x, end = bar) print() print(grid_line * x, end = plus) print_grid(5,3)
4eb0fd45ed58ab5e57d6dba2518fab2cc325b46a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kyle_lehning/Lesson04/book_trigram.py
2,987
4.3125
4
# !/usr/bin/env python3 import random import re import os def build_trigrams(all_words): """ build up the trigrams dict from the list of words returns a dict with: keys: word pairs values: list of followers """ trigrams = {} for idx, word in enumerate(all_words[:-2]): word_pair = word + " " + all_words[idx + 1] trigrams.setdefault(word_pair, []) trigrams[word_pair].append(all_words[idx + 2]) return trigrams def read_in_data(f_name): """ read all text from Gutenburg book returns a string with all the words from the book """ file_text = "" with open(f_name, "r") as file: for line in file: file_text += line.lower() updated_text = remove_punctuation(file_text) return updated_text def remove_punctuation(p_string): """ take an input string and remove punctuation, leaving in-word - and ' """ # (\b[-']\b) is a regular expression that captures intra-word ' and - in group(1) # the \b states that it is within a word, not at the end # |[\W_] is negated alpha num, same as [^a-zA-Z0-9], so captures all non alpha p = re.compile(r"(\b[-']\b)|[\W_]") # in the sub function check if it is captured in group(1) and if so restore it, else replace punctuation with " " updated_text = p.sub(lambda m: (m.group(1) if m.group(1) else " "), p_string) return updated_text def make_words(input_string): """ break a string of words into a list returns an ordered list of all words. """ all_words = input_string.split() return all_words def build_text(pairs): """ take a dictionary trigram and make a story returns a string story. """ first_key = random.choice(list(pairs.keys())) list_of_words = first_key.split() desired_sentence_length = random.randint(15, 20) # Randomize how long to make the sentence sentence_length = 0 while True: current_key = list_of_words[-2:] current_key_string = " ".join(map(str, current_key)) if current_key_string in pairs.keys(): next_word = random.choice(pairs[current_key_string]) list_of_words.append(next_word) sentence_length += 1 else: break if sentence_length == desired_sentence_length: break list_of_words[0] = list_of_words[0].capitalize() # Make first letter capital list_with_cap = ["I" if x == "i" else x for x in list_of_words] # Make I capital return (" ".join(list_with_cap)) + "." if __name__ == "__main__": filename = (input("Enter the path of your file: ")).replace(r'"', '') # remove quotes if copy as path used if os.path.exists(filename): in_data = read_in_data(filename) words = make_words(in_data) word_pairs = build_trigrams(words) new_text = build_text(word_pairs) print(new_text) else: print("I did not find the file at, "+str(filename))
c61e350a8d60402e7d6d5e05dba7fee0632ca92f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/nick_miller/lesson03/strformat_lab.py
4,004
4.46875
4
#!/usr/bin/env python3 """PY210_SP - 3.3 - strformat_lab author: Nick Miller""" # Task 01 tuple1 = (2, 123.4567, 10000, 12345.67) # produce: 'file_002 : 123.46, 1.00e+04, 1.23e+04' """ 1. The first element is used to generate a filename that can help with file sorting. The idea behind the “file_002” is that if you have a bunch of files that you want to name with numbers that can be sorted, you need to “pad” the numbers with zeros to get the right sort order. 2. The second element is a floating point number. You should display it with 2 decimal places shown. 3. The third value is an integer, but could be any number. You should display it in scientific notation, with 2 decimal places shown. 4. The fourth value is a float with a lot of digits – display it in scientific notation with 3 significant figures. """ print("file_{:03d} : {:.2f}, {:.2e}, {:.2e}".format(*tuple1)) print() # Task 02 """ Using your results from Task One, repeat the exercise, but this time using an alternate type of format string (hint: think about alternative ways to use .format() (keywords anyone?), and also consider f-strings if you’ve not used them already). """ print(f"file_{tuple1[0]:03d} : {tuple1[1]:.2f}, {tuple1[2]:.2e}, {tuple1[3]:.2e}") print() # or print("file_{:03d} : {:8.2f}, {:.2e}, {:.2e}".format(2, 123.4567, 10000, 12345.67)) print() # Task 03 """ Rewrite: "the 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3) to take an arbitrary number of values. Hint: You can pass in a tuple of values to a function with a *: """ def formatter(inTuple): """print out arbitrary length tuples""" tcounter = "the {} numbers are: ".format(len(inTuple)) if len(inTuple) > 0: tcounter += "{}".format(inTuple[0]) for num in inTuple[1:]: tcounter += ", {}".format(num) return tcounter testTuple = (1, 2, 3, 4, 5, 6, 7, 8) print(formatter(testTuple)) print() # Task 04 """ Given a 5 element tuple: ( 4, 30, 2017, 2, 27) use string formatting to print: '02 27 2017 04 30' Hint: use index numbers to specify positions. """ tupleshuffle = (4, 30, 2017, 2, 27) # Task 05 """ Given the following four element list: ['oranges', 1.3, 'lemons', 1.1] Write an f-string that will display: The weight of an orange is 1.3 and the weight of a lemon is 1.1 Now see if you can change the f-string so that it displays the names of the fruit in upper case, and the weight 20% higher (that is 1.2 times higher). """ fruitlist = ['oranges', 1.3, 'lemons', 1.1] print(f"The weight of an {fruitlist[0][:-1]} is {fruitlist[1]} \ and the weight of a {fruitlist[2][:-1]} is {fruitlist[3]}.") print() print(f"The weight of an {fruitlist[0][:-1].upper()} is {fruitlist[1]*1.2} \ and the weight of a {fruitlist[2][:-1].upper()} is {fruitlist[3]*1.2}.") print() # this one is extra, but for fun (rounding to one decimal place) print(f"The weight of an {fruitlist[0][:-1].upper()} is {fruitlist[1]*1.2:.1f} \ and the weight of a {fruitlist[2][:-1].upper()} is {fruitlist[3]*1.2:.1f}.") print() # Task 06 """ Write some Python code to print a table of several rows, each with a name, an age and a cost. Make sure some of the costs are in the hundreds and thousands to test your alignment specifiers. """ forTable = (["Henry", 5, 300], ["River", 0.2, 6000], ["Alicia", 35, 200], ["Daddio", 36, 8000]) key = ["name", "age", "cost"] row1 = forTable[0] row2 = forTable[1] row3 = forTable[2] row4 = forTable[3] print(f"{key[0]:<8}{key[1]:<8}{key[2]:>8}") print(f"{row1[0]:<8}{row1[1]:<8}{row1[2]:>8.2f}") print(f"{row2[0]:<8}{row2[1]:<8}{row2[2]:>8.2f}") print(f"{row3[0]:<8}{row3[1]:<8}{row3[2]:>8.2f}") print(f"{row4[0]:<8}{row4[1]:<8}{row4[2]:>8.2f}") print() # Extra """ And for an extra task, given a tuple with 10 consecutive numbers, can you work how to quickly print the tuple in columns that are 5 characters wide? It can be done on one short line! """ tuplex = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(" ".join(["{:<5}"] * len(tuplex)).format(*tuplex)) # new push
85643b0394dde171316c7a050050df5a71726ac1
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jack_anderson/lesson05/mailroom_pt3.py
6,377
3.921875
4
#!/usr/bin/env python3 """ Jack Anderson 02/18/2020 UW PY210 Mailroom assignment part 3 """ from datetime import date # The list of donors and their amounts donated donors_list = [ ['Bubbles Trailer',[1500.99, 2523, 3012]], ['Julien Park',[2520.92, 1623.12]], ['Ricky Boys',[345.56, 5123.25]], ['Jack Anderson',[1044, 2232, 4123.56]], ['Lacey Coffin Greene',[1500.32, 625.34, 1305, 340.78]] ] donors_dict = { donor[0]:donor[1] for donor in donors_list} def create_file(name, template): """ Action to create a file containing email template :param name: Name of donor :param template: Email template to use """ x = get_date() z = name.replace(" ", "_") with open(f'{z}_{x}.txt', 'w') as f: f.write(template) print(f"Email file '{z}_{x}.txt' has been created for {name}") def prompt_name(): # Return the name entered by user name = safe_input("Enter the full name of the donor " "(enter 'q' to cancel or 'list' to view a list of donors): ", is_name=True) return name def prompt_amount(): # Return the donation amount entered by user donation = safe_input("Please enter a donation amount " "(enter 'q' to cancel): $ ",is_name=False) return donation def list_names(): # Return a list of donors donors = list(donors_dict) return donors def add_items(name, donation): """ Action to add items to the donor_dict :param name: Donor name :param donation: Donation made by donor :return: Donor name, Donor Donation """ donated = [] donated.append(float(donation)) if name in donors_dict.keys(): donations = donors_dict[name] total = donated + donations donors_dict[name] = total else: donors_dict[name] = donated return name, donation def donor_details(name, donations): """ Action to summarize the details of a donor in the list :param name: Name of the donor :param donations: Donations made by the donor :return: Name of donor, total amount donated, number of donations donor made, avg donation of donor """ num_donations = len(donations) total_donated = sum(donations) avg_donation = total_donated / num_donations report_template(name, total_donated, num_donations, avg_donation) def report_template(name, total, count, avg): """ Action to print out a report using the same template for all donors :param name: Name of donor :param total: Total Amount donated from donor :param count: Total amounts of donations made :param avg: The average donation made """ x = name y = total c = count a = float(avg) z = '{name:<21}\t$ {total:>{width}.2f}\t{count:^{width}}\t$ {avg:>{width}.2f}' \ .format(name=x, total=y, count=c, avg=a, width=10) print(z) def send_email(name, donation): """ Action to print out donor email :param name: Name of the donor :param donation: The amount provided by the donor """ template = (f"Hello {name},\n\n" f"Thank you for your recent gift of ${donation:.2f}! \n" "We will use your gift to help with costs for our upcoming play! \n" "Thank you for giving!\n\n" "Best Regards, \n" "The Blanchford Community Center!") create_file(name, template) def print_report_header(): # Print a header for the report print() print('{name:<21}\t| {total:^{width}}\t| {count:^{width}}\t| {avg:>{width}}' \ .format(name='Donor Name', total='Total Given', count='Num Gifts', avg='Average Gift', width=10)) print("=" * 70) def create_report(): # Action to call report generation functions print_report_header() action = [donor_details(name, donations) for name, donations in (sorted(donors_dict.items(), key = lambda x:(sum(x[1]), x[0]), reverse=True))] return action def send_thanks(): # Action to create Thank you email for single person x, y = add_items(prompt_name(), prompt_amount()) send_email(x, y) def send_all_thanks(): # Action to create Thank you email for ALL persons action = [send_email(name, donation[0]) for name, donation in donors_dict.items()] return action def get_date(): # Return the current date today = date.today() return today def start(): """ Action to prompt user to select various menu items or to close the program. Checks in place to ensure user enters a numerical key. """ while True: mailroom_start = {1: send_thanks, 2: create_report, 3: send_all_thanks, 4: quit} try: print() action = input("Select a number to perform one of the following actions...\n" "1 -- Send a Thank You to a single donor \n" "2 -- Create a Report. \n" "3 -- Send a Thank You to all donors \n" "4 -- Quit \n") x = int(action) mailroom_start.get(x)() # except (ValueError, TypeError): # print("Not a valid option: Please enter a number from 1 to 4") except KeyboardInterrupt: print() quit() def safe_input(prompt, is_name): """ Check user prompt and perform action based on user input if no conditions are met :param prompt: A string to display to the user when requesting input :param is_name: set to True for name check, set to False for donation check :return: Return user input or re-prompt user for input if invalid input received """ try: user_input = input(prompt) if len(user_input) == 0: print("Must enter a value") return safe_input(prompt, is_name) elif user_input.lower() == 'q': start() else: if is_name == True: if user_input.lower() == 'list': list_names() return prompt_name() else: return user_input else: try: return float(user_input) except ValueError: print("You must enter a numerical value") return prompt_amount() except(KeyboardInterrupt): print() quit() if __name__ == '__main__': start()
d962d3b9a9df195b320e91bd054e9ea78aaf56c6
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/grant_dowell/Lesson_08/test_circle.py
1,390
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 9 20:13:36 2020 @author: travel_laptop """ import math import unittest as ut from circle import * def test_properties(): c = Circle(10) assert c.radius == 10 assert c.diameter == 20 print(c.area) assert c.area == math.pi * 100 c.diameter = 6 assert c.radius == 3 def test_diameter_init(): c = Circle.from_diameter(8) assert c.radius == 4 def test_print(): c = Circle(6) print(c) assert str(c) == 'Circle with radius: 6.000000' assert repr(c) == "Circle(6.00)" def test_math(): c1 = Circle(2) c2 = Circle(4) c3 = c1 + c2 print(c3) assert c3.radius == 6 c4 = c1 * 3 print(c4) assert c4.radius == 6 def test_compares(): c1 = Circle(2) c2 = Circle(4) assert (c1 > c2) is False assert c1 < c2 assert (c1 == c2) is False c3 = Circle(4) assert c2 == c3 def test_sort(): circles = [Circle(6), Circle(7), Circle(2), Circle(1)] sorted_circles = [Circle(1), Circle(2), Circle(6), Circle(7)] circles.sort() assert circles == sorted_circles def test_sphere_volume(): s = Sphere(2) assert s.volume == 4/3 * math.pi * 8 def test_sphere_print(): s = Sphere(6) print(s) assert str(s) == 'Sphere with radius: 6.000000' assert repr(s) == "Sphere(6.00)"
3e41359bba03ed238200f4413d85f70325006266
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/erik_oien/lesson01/warmup_1.py
1,419
3.515625
4
# sleep_in def sleep_in(weekday, vacation): if not weekday or vacation: return True else: return False # monkey_trouble def monkey_trouble(a_smile, b_smile): if a_smile and b_smile: return True if not a_smile and not b_smile: return True return False # sum_double def sum_double(a, b): sum = a+b if a == b: return sum * 2 return sum # diff21 def diff21(n): if n <= 21: return 21 - n return abs(21 - n) * 2 # parrot_trouble def parrot_trouble(talking, hour): if talking: if 7 <= hour <= 20: return False else: return True return False # makes10 def makes10(a, b): if a == 10 or b == 10 or a+b == 10: return True return False # near_hundred def near_hundred(n): return(abs(n-100) <= 10 or abs(n-200) <= 10) # pos_neg def pos_neg(a, b, negative): if negative: if a < 1 and b < 1: return True else: return False if (a < 1 and b >= 1) or (a >= 1 and b < 1): return True return False # not_string def not_string(str): if str[0:3] == "not": return str return "not " + str # missing_char def missing_char(str, n): return str[:n] + str[n+1:] # front_back def front_back(str): if len(str) <= 1: return str return str[len(str)-1] + str[1:-1] + str[0] # front3 def front3(str): if len(str) < 3: return str + str +str new_str = str[0:3] return new_str + new_str + new_str
01a438810a58c2b072b8a6823796408cf91bcb44
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chelsea_nayan/lesson02/fizzbuzz.py
793
4.5
4
# chelsea_nayan, UWPCE PYTHON210, Lesson02:Fizz Buzz Exercise # This function prints the numbers from low to high inclusive. For multiples of three, "Fizz" is printed instead of the numer and for multiples of five, "Buzz" is printed. If the number both divisble by three and five, it prints out "FizzBuzz" def fizzbuzz(low, high): # Parameters takes in the range of numbers to print that users can change i = low while i <= high: # This while loop goes through from low to high if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0 and i % 5 != 0: print("Fizz") elif i % 5 == 0 and i % 3 != 0: print("Buzz") else: print(i) i += 1 #The example given in the lesson page fizzbuzz(1,100)
a052bf6914dc8f5f93d2b1f236a46982f6bb9c4e
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Yue_Ma/Lesson08/circle.py
1,653
4.09375
4
#!/usr/bin/env python3 import math class Circle(object): def __init__(self, radius): self.radius = radius @property def diameter(self): diameter = self.radius * 2 return diameter @diameter.setter def diameter(self, diameter): self.radius = diameter / 2 @property def area(self): area = self.radius ** 2 * math.pi return area @classmethod def from_diameter(cls, diameter): radius = cls(diameter / 2) return radius def __str__(self): return f'Circle with radius: {self.radius}' def __repr__(self): return f'Circle({self.radius})' # Numeric Protocol def __add__(self, other): return Circle(self.radius + other.radius) def __mul__(self, other): return Circle(self.radius * other) def __eq__(self, other): return self.radius == other.radius def __lt__(self, other): return self.radius < other.radius def __le__(self, other): return self.radius <= other.radius def __ge__(self, other): return self.radius >= other.radius def __gt__(self, other): return self.radius > other.radius def __ne__(self, other): return self.radius != other.radius class Sphere(Circle): def __str__(self): return f'Sphere with radius: {self.radius}' def __repr__(self): return f'Sphere({self.radius})' @property def volume(self): volume = self.radius ** 3 * math.pi * 4 / 3 return volume @property def area(self): area = self.radius ** 2 * math.pi * 4 return area
f7b291f84604918079f08f1a86bb442b0fa2c885
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/phrost/Lesson03/Exercises/Series_2.py
400
3.84375
4
fruit = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruit) del fruit[-1] print(fruit) fruit_2 = fruit[:] + fruit[:] print(fruit_2) polling_active = True while polling_active: fruit_d = input('Please select a fruit to delete: ') if fruit_d in fruit_2: fruit_2.remove(fruit_d) if fruit_d in fruit_2: fruit_2.remove(fruit_d) polling_active = False print(fruit_2)
30901cb116e213843aa072d76b18e6073d493d05
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mattcasari/lesson01/logic-2/lone_sum.py
227
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- def lone_sum(a, b, c): temp = [a, b, c] final_list = [] for num in temp: if temp.count(num) == 1: final_list.append(num) return sum(final_list)
b9929687fa1469adb1e68e0e3323051183ef7094
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/karl_perez/lesson05/mailroom3.py
4,015
3.9375
4
#!/usr/bin/env python3 #Mailroom part 3 import sys #donors donors = [["Krystal Perez", 50.00, 250.00], ["Eddie Lau", 32.50], ["Jimmy Jack", 200.00, 350.00, 400.00], ["Grace Cool", 120.00, 75.00], ["Adriel Molina", 45.00, 450.00]] # menu prompt def menu(): #Tell the user what their options are. Ask for an input. print('') print('Welcome to the mailroom tool. Please select an action:') print('1 - Send a Thank You') print('2 - Create a Report') print('3 - Send letters to all donors') print('4 - Quit') #Send user input back to main function to be analyzed. return input() # Send a thank you def send_thanks(donor_comprehension): print("To view current donors, type 'list' ") while True: names = input("Please provide the Full Name of a donor:") if names.lower() == 'list': for e in donor_comprehension: print(e) else: break try: amount = input("Please enter a donation amount:\n") except ValueError: print("\n Invalid Amount. Please Enter a valid number \n") if names in donor_comprehension: donor_comprehension[names].append(float(amount)) else: donor_comprehension.update({names: [float(amount)]}) letter = {"donor_name": names, "donation_amount": float(amount)} print("Dear {donor_name}, we appreciate your generosity in the donation amount of ${donation_amount:.2f}.\n".format(**letter)) #create a report that calculate Donor Name, Total Given, Number of donatons, and the avarage amount of thier donations def write_a_report(donor_comprehension): Title = "\n{:<12}{:<6}{:<15}{}{:<10}{}{:<10}".format(*('Donor Name','|','Total Given','|','Num Gifts','|','Average Gift')) print(Title) print ('-'*len(Title)) #Create donor report using comprehension donor_report = [calculator(donor_comprehension,names) for names in donor_comprehension] #Sort the list by the first value (Total Gift) donor_report = sorted(donor_report,reverse=True) for i in range(len(donor_comprehension)): print('{:<20} $ {:>15.2f} {:>10} $ {:>15.2f}'.format(donor_report[i][3], donor_report[i][0], donor_report[i][1], donor_report[i][2])) #New function to calculate report (makes comprehension more readable) def calculator(donor_comprehension, names): total = float(sum(donor_comprehension[names])) number = len(donor_comprehension[names]) average = total/number return total, number, average, names def send_letters_all(donor_comprehension): for name in donor_comprehension: if len(donor_comprehension[name]) == 1: gift = str(donor_comprehension[name][0]) else: values = '' for donations in range(len(donor_comprehension[name])): if donations == len(donor_comprehension[name])-1: values = values + 'and ' + '$' + str(donor_comprehension[name][donations]) else: values = values + '$' + str(donor_comprehension[name][donations]) + ', ' gift = values with open(name + '.txt', 'w') as file: file.write(f'Dear {name},\n We appreciate your generosity in the donation amount of ${gift}.\n Sincerely, The Charity Team') def exit_program(donor_comprehension): print("Bye!") sys.exit() # exit the interactive script if __name__ == "__main__": #Create donor dictionary using comprehension donor_comprehension = {donor[0] : donor[1:] for donor in donors} dispatch = {"1": send_thanks, "2": write_a_report, "3": send_letters_all, "4": exit_program} #Prompt the user to do something. Stay here unless user selects a quit item. while True: #Call the opening menu function user = menu() #Analyze responses and call related function or quit. #if user in switch_dict: try: dispatch[user](donor_comprehension) except KeyError: print('Please select a value 1-4')
bef1092d43e26d2806fa42416f04588a8e5da860
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kgolenk/lesson03/strformat_lab.py
3,949
3.671875
4
#!/usr/bin/env python3 # ---------------------------------------------------------------------------- # # Title: Lesson 03 # Description: Slicing Lab # ChangeLog (Who,When,What): # Kate Golenkova, 10/16/2020, Created script # Kate Golenkova, 10/18/2020, Changed script # Kate Golenkova, 10/19/2020, Changed script # ---------------------------------------------------------------------------- # # Data ----------------------------------------------------------------------- # # Task One print("Task One") # Variables ------------------------------------------------------------------ # a = (2, 123.4567, 10000, 12345.67) # Functions ------------------------------------------------------------------ # def format_string(): """ Format each element in tuple as a string and print string """ form = 'file_{:03d} : {:.2f}, {:.2e}, {:.2e} ' print(form.format(*a)) format_string() # Task Two ------------------------------------------------------------------- # print("\nTask Two") # Variables ------------------------------------------------------------------ # # Functions ------------------------------------------------------------------ # def f_func(): """ Format each element in tuple using keywords and f-string and print string """ file, num1, num2, num3 = a print(f'file_{file:03d} : {num1:.2f}, {num2:.2e}, {num3:.2e} ') f_func() # Task Three------------------------------------------------------------------- # print("\nTask Three") # Variables ------------------------------------------------------------------ # tuple1 = (1, 3, 2, 5, 1, 6, 9) # Functions ------------------------------------------------------------------ # def formatter(tuple1): """ Dynamically build up the format string to accommodate the length of the tuple, Returns a string. """ n = str(len(tuple1)) form = "" for i in tuple1: form += '{:d}, ' print(" The " + n + " numbers are: " + form.format(*tuple1)) return form.format(*tuple1) formatter(tuple1) formatter(tuple1*2) # Task Four ------------------------------------------------------------------ # print("\nTask Four") # Variables ------------------------------------------------------------------ # tuple2 = ( 4, 30, 2017, 2, 27) # Functions ------------------------------------------------------------------ # def form_tuple(tuple2): """ Returns tuple with other order""" print(f'{tuple2[-2:] + tuple2[2:len(tuple2)-2] + tuple2[:2]}') form_tuple(tuple2) # Task Five ------------------------------------------------------------------ # print("\nTask Five") # Variables ------------------------------------------------------------------ # fr = ['oranges', 1.3, 'lemons', 1.1] # Functions ------------------------------------------------------------------ # def f_str(fr): """ F-string displays list in certain order. Also, f-string format string with upper case letters and modified weight """ fr[0] = 'orange' fr[2] = 'lemon' print(f'The weight of an {fr[0]} is {fr[1]} and the weight of a {fr[2]} is {fr[3]}') print(f'The weight of an {fr[0].upper()} is {fr[1]*1.2} and the weight of a {fr[2].upper()} is {fr[3]*1.2}') f_str(fr) # Task Six ------------------------------------------------------------------ # print("\nTask Six") # Variables ------------------------------------------------------------------ # A = [ [ 'The House', 30, 500000.00], [ 'The Boat', 8, 120000.00], [ 'The Car', 2, 50000.00] ] aa = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100) # Functions ------------------------------------------------------------------ # def format_table(A): """ Returns rows in a table with all the items/ages/prices """ for i in A: print('| Name: {0:10} | Age: {1:5} years | Price: {2:,} dollars |'.format(*i)) format_table(A) # Print the tuple aa in columns that are 5 characters wide print("The numbers are: ") print("\n".join(len(aa)*["{:5}"]).format(*aa))
a57426f9e622fedf3f5da2e541a132a1f199ca9a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/pkoleyni/Lesson02/fizz_Buzz.py
437
4.03125
4
def multiples_of_num(num1, num2): if num1%num2 ==0: return True else: return False def fizz_buzz(n): for num in range(1, n+1): if multiples_of_num(num, 3) and multiples_of_num(num, 5): print('FizzBuzz') elif multiples_of_num(num, 3): print('Fizz') elif multiples_of_num(num, 5): print('Buzz') else: print(num) fizz_buzz(100)
60c4c7cebe6342a7735d5633ec26ea31b4adc1c3
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/thomas_sulgrove/lesson02/series.py
1,899
4.28125
4
#!/usr/bin/env python3 """ a template for the series assignment #updated with finished code 7/29/2019 T.S. """ def fibonacci(n): series = [0,1] #Define the base series values in a list while len(series) < n + 1: #add one so normalize lenth and index number series.append(sum(series[-2:])) #Add last two variables and append to list return series[n] #return the nth value def lucas(n): series = [2,1] #Define the base series values in a list while len(series) < n + 1: #add one so normalize lenth and index number series.append(sum(series[-2:])) #Add the variables and append on to the list return series[n] #return the nth value def sum_series(n, n0=0, n1=1): #default values are for fibonacci sequence series = [n0, n1] #Define the base series values in a list while len(series) < n + 1: #add one so normalize lenth and index number series.append(sum(series[-2:])) #Add the variables and append on to the list return series[n] #return the nth value if __name__ == "__main__": # run some tests assert fibonacci(0) == 0 assert fibonacci(1) == 1 assert fibonacci(2) == 1 assert fibonacci(3) == 2 assert fibonacci(4) == 3 assert fibonacci(5) == 5 assert fibonacci(6) == 8 assert fibonacci(7) == 13 assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(4) == 7 # test that sum_series matches fibonacci assert sum_series(5) == fibonacci(5) assert sum_series(7, 0, 1) == fibonacci(7) # test if sum_series matched lucas assert sum_series(5, 2, 1) == lucas(5) # test if sum_series works for arbitrary initial values assert sum_series(0, 3, 2) == 3 assert sum_series(1, 3, 2) == 2 assert sum_series(2, 3, 2) == 5 assert sum_series(3, 3, 2) == 7 assert sum_series(4, 3, 2) == 12 assert sum_series(5, 3, 2) == 19 print("tests passed")
c35f35adacf25a0d61b409bdddf6dbef8f98963e
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/zhen_yang/lesson06/test_centered_average.py
1,009
4.09375
4
""" test code for the centered_average.py centerted_average.py returns the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int int division to produce the final average. You may assume that the array is length 3 or more. """ from centered_average import centered_average def test_regular(): list = [1, 2, 3, 4, 100] assert centered_average(list) == 3 def test_repeated_smallest(): list = [1, 1, 5, 5, 10, 8, 7] assert centered_average(list) == 5 def test_repeated_largest(): list = [1, 5, 5, 10, 10, 8, 7] assert centered_average(list) == 7 def test_repeated_smallest_largest(): list = [1, 1, 5, 5, 10, 10, 10, 8, 7] assert centered_average(list) == 6 def test_negative(): list = [-10, -4, -2, -4, -2, 0] assert centered_average(list) == -3
7f06ec741747e5551ac76fff6afd330278d3d761
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mark_mcduffie/Lesson5/mailroom_part3.py
4,627
3.875
4
''' Mark McDuffie 3/20/19 Mailroom part 2 It should have a data structure that holds a list of your donors and a history of the amounts they have donated. This structure should be populated at first with at least five donors, with between 1 and 3 donations each. You can store that data structure in the global namespace. The script should prompt the user (you) to choose from a menu of 3 actions: “Send a Thank You”, “Create a Report” or “quit”. *edited from mailroom part 1, uses dicts where appropriate ''' import pathlib import operator import os #Original Donor list, used and added upon in the program #conatins two columns for first and last name, and up to 3 more for donation amounts donors = { "Jim Johnson": [20000.0, 3500.0, 1600.0], "Mike Lee": [10000.0, 450.0, 1000.0], "Joe Smith": [100.0, 50.0], "Bob Miller": [900.0, 1200.0], "Steve James": [100000.0] } #The script should prompt the user (you) to choose from a menu of 3 actions: #“Send a Thank You”, “Create a Report” or “quit” def prompt(): choice = input("You have the following options: \n 1: Send a Thank You \n 2: Send Letters to all Donors " "\n 3: Create a Report \n 4: Quit \n") return choice #Prints a nicely formatted email to donor def print_email(name, amount): print("Dear {},\n \tThank you for your donation of ${:,.2f}. \nYour generosity is greatly appreaciated, " "we \nlook forward to hearing from you again. \nCheers, \nThe Mailroom".format(name, amount)) #Used in Thank you method, allows us to access just a list of donor names to check def donor_names(donors): for key in donors.keys(): name = key print(name) #Checks whether the new donor already exists in the list or not def exists(name): for i in donors: if name == i[0]: return True #thank you method allows user to add donor and/or donation amount to the list #Calls other methods print_list, and exists, to show formatted list, and check if donor exists def single_thank_you(): donor = input("Please enter Donor name (first and last), \nor enter 'list' if you want to see the full list of Donors. \n") try: if donor.lower() == 'list': #shows formatted list if user wants to check donor_names(donors) else: amount = float(input("How much did " + donor + " donate? ")) if donor in donors: donors[donor].append(amount) else: donors[donor] = [amount] #Appends new donor and amount if donor does not exist print_email(donor, amount) #Method to end official letter once name and donation are entered except ValueError as error_message: print(error_message) return main() #Sends a thank you to ever donor on the list, creating individual text files def send_all(): try: recipients = ({'name': item[0], 'total': str(sum(item[1]))} for item in donors.items()) for recipient_name in recipients: with open('{name}.txt'.format(**recipient_name), 'w') as f: f.write("Dear {name},\n \tThank you for your donation of ${total}. " "\nYour generosity is greatly appreaciated, we \nlook forward to hearing from you again. " "\nCheers, \nThe Mailroom".format(**recipient_name)) except FileExistsError as error_message: print(error_message) print("Letter were created and are in the {} directory.".format(os.getcwd())) #Creates a well formatted report, counting every person's donation and calcuting their average def report(): sorted_donors = sorted(donors.items(), key=operator.itemgetter(1), reverse=True) print("Donor Name" + " " * 16 + "| Total Given | Num Gifts | Average Gift") print("-" * 66) for i in sorted_donors: print("{:<25} ${:>12.2f} {:>9d} ${:>11.2f}".format(i[0], sum(i[1]), len(i[1]), sum(i[1])/len(i[1]))) #generates statistics for each row in the report # adds all donations for each name # counts the total number of gifts for each donor #calculates average donation return main() #Main function for interactions def main(): while True: choice = int(prompt()) choice_Dict = { 1: single_thank_you, 2: send_all, 3: report, 4: quit } if choice in choice_Dict: choice_Dict.get(int(choice))() else: print("Please enter a choice number between 1 and 4") if __name__ == '__main__': main()
fd4077a9c410e963bf9adf65e579c0f20bcd002d
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chrissp/lesson05/mailroom.py
4,482
3.640625
4
import sys # Global Variables donor_db = [{"name": "William Gates, III", "donations": [653772.32, 12.17]}, {"name": "Jeff Bezos", "donations": [877.33]}, {"name": "Paul Allen", "donations": [663.23, 43.87, 1.32]}, {"name": "Mark Zuckerberg", "donations": [1663.23, 4300.87, 10432.0]}, ] prompt = "\n".join(("Welcome to the mailroom!", "Please choose from below options:", "1 - Send a Thank You to a Single Donor", "2 - Create a Report", "3 - Send Thank you to All Donors", "4 - Quit", ">>> ")) letter_template = ("Dear {donor_name},\n\tThank you for your generous donation of ${last_donation}!\n" "\tYour {total_donations} donations wll be used to supply children with laptop batteries.\n\n" "Greatest thanks from,\n\tScott's Tots Foundation\n") def sort_donations(donor_entry): """ Sort Function to return donor donation total for sorting donor list (by donations) :param donor_entry: Donor database entry to return donation total for sorting :return: Returns donor donation total for sorting """ return sum(donor_entry["donations"]) def send_thanks(): """ Send Thanks function that takes a user input for name and donation. """ user_input = input("\n What is the Full Name of the donor?").title() this_donor = "" if user_input == "Quit": main() if user_input == "List": for person in donor_db: print(person["name"]) send_thanks() else: this_donation = input("What is the donation amount?") if this_donation.title() == "Quit": main() else: try: this_donation = float(this_donation) except ValueError: print("Donation must be a number.") send_thanks() else: for person in donor_db: if user_input.lower() == person["name"].lower(): this_donor = person person["donations"].append(this_donation) break if this_donor == "": donor_db.append({"name": user_input, "donations": [this_donation]}) this_donor = donor_db[-1] this_letter = {'donor_name': this_donor["name"], 'last_donation': this_donation, 'total_donations': len(this_donor["donations"])} # Build thank you email print(letter_template.format(**this_letter)) def create_report(): """ Print Report function of current donor database. """ # Sort the donor database by donations (donation total) sorted_donors = sorted(donor_db, key=sort_donations, reverse=True) # Print table header print('Donor Name | Total Given | Num Gifts | Average Gift ') print('----------------------------------------------------------------------') for donor in sorted_donors: donor_name = donor["name"] num_gifts = len(donor["donations"]) total_gift = 0 for donation in donor["donations"]: total_gift += donation avg_gift = str(round(total_gift / num_gifts, 2)) # Print formatted donor info line print(f"{donor_name:26} ${round(total_gift, 2):>15} {num_gifts:^11d} ${avg_gift:>15}") def send_thanks_all(): for person in donor_db: this_letter = {'donor_name': person["name"], 'last_donation': person["donations"][-1], 'total_donations': len(person["donations"])} # Build thank you email file_name = person["name"] + ".txt" with open(file_name, 'w') as outfile: outfile.write(letter_template.format(**this_letter)) print(f"{len(donor_db)} 'Thank You' letter files have been created!") def quit_program(): print("See you next time!") sys.exit() def main(): nav_dict = {1: send_thanks, 2: create_report, 3: send_thanks_all, 4: quit_program} while True: response = int(input(prompt)) if not response in nav_dict: print("Sorry, that isn't a valid selection.") main() nav_dict.get(response)() if __name__ == "__main__": main()
a28d51e710b65eb777c69270cf0a4c250ad195fa
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shumin/lesson02/fizz_buzz.py
378
4.03125
4
# This program prints from 1 to 100 # Multiples of 3 prints Fizz # Multiples of 5 prints Buzz # Multiples of 15 prints FizzBuzz def fizz_buzz(): for i in range(1, 101): if i % 15 == 0: print("FizzBuzz") elif i % 5 == 0: print("Buzz") elif i % 3 == 0: print("Fizz") else: print(i) fizz_buzz()
a0967efe83f65fa7f74d1edd3f8157ce6ee0aed4
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chasedullinger/lesson04/file_parsing.py
651
3.78125
4
#!/usr/bin/env python3 # PY210 Lesson 04 File Parsing - Chase Dullinger input_file = "students.txt" languages = {} with open(input_file, "r") as file: lines = file.readlines() for line in lines[1:]: nickname_and_languages = line.split(":")[1].split(",") for item in nickname_and_languages: cleaned_item = item.replace("\n", "").replace(" ", "") if cleaned_item and not cleaned_item[0].isupper(): languages.setdefault(cleaned_item, 0) languages[cleaned_item] += 1 print(languages.keys()) print("Language: Number of times") for k, v in languages.items(): print(f"{k}: {v}")
99dc4ca468a929a6770561473da628bd3022cc99
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/rick_halsell/lesson02/exercisetwo.py
4,289
3.9375
4
# Printing a Grid # function to print the top line of the box def full_line_func(): num_full_line = [ print('+ - - - - + - - - - +') for num_full_line in range(1)] return # function to print the second line of the box def pipe_space_func(): num_pipe = [ print('| | |', end=' ') for num_pipe in range(1)] print() return # function to call the functions to create the box size = 4 def box_func(): full_line_func() for i in range(4): pipe_space_func() full_line_func() for i in range(4): pipe_space_func() full_line_func() return # calling the function box_func() print() # part 2 # Printing a Grid with size options # function to print the top line of the box print('Part 2') def plusfunc(): plussymbol = [print('+', end=' ') for plussymbol in range(1)] return # function to print the second line of the box def tabfunc(): tabsymbol = [print('-', end=' ') for tabsymbol in range(1)] return def pipefunc(): pipesymbol = [print('|', end=' ') for pipesymbol in range(1)] return def spacefunc(): spacesymbol = [print(' ' * ((size * 2)-1) , end=' ') for spacesymbol in range(1)] return # function to call the functions to create the box def box_size_func(size): # function to print the second line of the box def pipe_space_func(): num_pipe = [ print('|', end=' ') for num_pipe in range(1)] num_space = [print(' ' * ((size * 2)-1) , end=' ') for num_space in range(1)] num_pipe = [ print('|', end=' ') for num_pipe in range(1)] num_space = [print(' ' * ((size * 2)-1), end=' ') for num_space in range(1)] num_pipe = [ print('|', end=' ') for num_pipe in range(1)] print() return plusfunc() # insert plus symbol for i in range(size): # insert dash symbol tabfunc() plusfunc() # insert plus symbol for i in range(size): # insert dash symbol tabfunc() plusfunc() # insert plus symbol print() for i in range(size): # instert pipe symbol pipe_space_func() plusfunc() # insert plus symbol for i in range(size): # insert dash symbol tabfunc() plusfunc() # insert plus symbol for i in range(size): # insert dash symbol tabfunc() plusfunc() # insert plus symbol print() for i in range(size): # instert pipe symbol pipe_space_func() plusfunc() # insert plus symbol for i in range(size): # insert dash symbol tabfunc() plusfunc() # insert plus symbol for i in range(size): # insert dash symbol tabfunc() plusfunc() # insert plus symbol print() return # calling the function box_size_func(7) # part 3 # Printing a Grid with units options # function to print the top line of the box print('Part 3') # function to call the functions to create the box # I need some help with trying to use to following function in the while loop to produce the # grid. # I'm receiving this error: TypeError: can't multiply sequence by non-int of type 'str' # I understand what the function is saying, I need to know how to work around this error. def plusfunc(units,size): #plussymbol = [print('+', ((* units * 2)), end=' ') for plussymbol in range(1)] #plussymbol = '+ ' + ('- ' * units) #print(plussymbol) plus = '+ ' + ('- ' * units) pipe = '| ' + (' '* (2 * size)) print(plus * pipe + '+') return plus # function to print the second line of the box def pipefunc(size): #dashsymbol = [print('-', end=' ') for dashsymbol in range(units)] #vertical = '| ' + (' '* (2 * size)) #print(vertical) pipe = '| ' + (' '* (2 * size)) return pipe def gridprinter3(units, size): plusfunc(units) pipefunc(size) #horizontal = '+ ' + ('- ' * size) #vertical = '| ' + (' '*(2*size)) #print(plusfunc(5) * dashfunc(2) + '+') #print(plusfunc(5))# * dashfunc(2)) #+ '+') #for plussymbol in range(units * size)) print(plusfunc(units) * pipefunc(size) + '+') #print(horizontal*square + '+') initial = 1 while initial <= units: j = 0 while j < size: print(plusfunc(units) + '|') j += 1 print(pipefunc(size) + '+') initial += 1 #gridprinter3(2,2) #boxrowfunc(8,2) plusfunc(8,2)
27c58d61171367d533d4c91546a8cf6806b970f0
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jerickson/Lesson9/mailroom/donor_models.py
6,696
3.703125
4
"""Contains the DonationData and Donor classes""" import os import re class Donor: """Holds specific donor data""" def __init__(self, name=""): # TODO remove KWARG """ Creates a new donor Parameters ---------- name : str, optional Donor Name, by default "", default raises error Raises ------ ValueError If no "name" is specified """ if not name: raise ValueError("Must enter a donor name.") self.name = name self.donations = [] @property def total_given(self): """ Return the sum of all the donor's donations. Returns ------- total_given: int or float The sum of donations """ return sum(self.donations) @property def total_gifts(self): """ Return the number of donations the donor has made. Returns ------- total_gifts: int The number of donations """ return len(self.donations) def add_donation(self, new_amount): """ Add a new donation to the donor's record. Parameters ---------- new_amount : int or float The new donation amount for the donor Raises ------ ValueError If donation amount is non-specified or is negative """ if not new_amount or new_amount <= 0: raise ValueError("Donation new_amount must be a positive number") self.donations.append(new_amount) def thank_you_latest(self): """ Return a personalized thank-you message to the donor for their latest donation. Returns ------- text: str Thank you message Raises ------ IndexError, subclass of LookupError If donor has not made any donations """ last_donation = self.donations[-1] # Raises LookupError(IndexError) if empty time_s = "times" if self.total_gifts > 1 else "time" text = ( f"Thank you {self.name}" f" for your donation of ${last_donation:.2f}!" f" You have donated {self.total_gifts:d} {time_s}" f" for a total of ${self.total_given:.2f}." ) return text def thank_you_overall(self): """ Return a personalized thank-you message to the donor for their overall donations. Returns ------- text: str Thank you message Raises ------ LookupError If donor has not made any donations """ if not self.donations: raise LookupError("Donor has not made any donations.") time_s = ( f"{self.total_gifts:d} donations" if self.total_gifts > 1 else "donation" ) # Grammer correction of "donation" vs "# donations" text = ( f"Thank you {self.name},\n\n" f"Your {time_s}" f" totaling ${self.total_given:.2f} will help us.\n\n" f"{'':>40}Best Regards,\n{'':>40}Jacob Erickson" ) return text class Record: """Holds all donation data for the charity""" def __init__(self): self.donors = {} def add_donor(self, new_donor_name): """ Adds a donor to the charity's record. Stores donors in dict{name: Donor Object} Parameters ---------- new_donor_name : str Name of new donor """ self.donors[new_donor_name] = Donor(name=new_donor_name) @property def donor_list(self): """ Return the list of donor names in record, sorted by decending total_given. Returns ------- list All Donor names sorted decending by donor's total_given """ return sorted( self.donors, key=lambda name: self.donors[name].total_given, reverse=True ) def compose_report(self): """ Return pretty-formatted report of all the donors. Produces a 'pretty' ASCII formatted table If no donors, return is empty formatted table. Donors are sorted in the report in decending order according to total-given amount. Uses double braces "{{}}" in format strings to dynamically update name field to accommodate long donor names without breaking report format. Returns ------- report_list : list of str List of strings for each row of the report. """ header_columns = ["Name", "Total Given", "# Gifts", "Average Gift"] report_list = [] # Create Name Field Dynamically longest_name = max(self.donor_list + ["Name"], key=len) name_field_dynamic = "{{:^{:d}}}".format(len(longest_name) + 2) # Format report lines report_header = "|{}| {{:^12}}|{{:^13}}| {{:^13}}|" report_header = report_header.format(name_field_dynamic).format(*header_columns) report_length = len(report_header) report_break = re.sub("[^|]", "-", report_header).replace("|", "+") report_end = "-" * report_length report_title = "|{{:^{:d}}}|".format(report_length - 2).format("Donor Report") # Append Report Title and Header report_list.extend([report_end, report_title, report_break, report_header]) # Append Sorted Donor Records for name in self.donor_list: total_given = self.donors[name].total_given if not total_given: # Exclude donors with 0 given continue num_gifts = self.donors[name].total_gifts donor_average = float(total_given / num_gifts) donor_string = "|{}| ${{:>12.2f}}|{{:^13d}}| ${{:>13.2f}}|".format( name_field_dynamic ).format(name, total_given, num_gifts, donor_average) report_list.extend([report_break, donor_string]) report_list.append(report_end) return report_list def save_all_donor_emails(self): """Write to disk thank-you emails for each donor.""" path = os.path.dirname(os.path.realpath(__file__)) file_id = 0 for donor_name, donor_data in self.donors.items(): try: thank_you_message = donor_data.thank_you_overall() except LookupError: # Skips donors with $0 donated continue file_name = f"Donor{file_id:03d}_{donor_name}_gitnore.txt" file_id += 1 with open(path + "\\" + file_name, "w") as file: file.write(thank_you_message)
50a9086efd36c837d28b017f435a767742778439
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/bcamp3/lesson03/mailroom.py
3,249
3.9375
4
#!/usr/bin/env python3 """ Mailroom script This script accepts user input to perform the following donation database tasks: 1 - Display the donor database list or update the donation database with a new donation. Then display a 'Thank You' message to the donor of the new donation. 2 - Display a donation database report 3 - Quit out of the script """ #creating the donor database using nested lists: donors = [['Katherine Elmhurst','David Anderson','Edward Hoffstein','Rebecca Manriquez','Callum Foxbright'], [[1000.,1500.,1900.] , [10865.,5750.] , [200.,200.,200.] , [1750.,1500.] , [130.75]]] def send_thank_you(): name = input('\nEnter the full name of the donor > ') if name == 'list': print('\nPrinting list of current donors :\n') for donor in donors[0]: print(' ',donor) send_thank_you(donors) else: proper_name = ' '.join([word.capitalize() for word in name.split(" ")]) if proper_name not in donors[0]: print('\nAdding donor to database :',proper_name) donors[0].append(proper_name) donors[1].append([]) else: print(f'\nFound donor {proper_name} in database.') amt = input('\nEnter a donation amount > $ ') famt = float(amt) index = donors[0].index(proper_name) donors[1][index].append(famt) print( '\nEMAIL MESSAGE :') print( ' ___________________________________________________________') print( ' Subject: THANK YOU !!! ') print( ' ') print(f' Dear {proper_name}, ') print( ' ') print(f' Thank you for your generous donation of ${famt:.2f}. ') print( ' Your donation will help our foundation achieve our goals. ') print( ' ') print( ' Regards,\n Foundation Leadership Team ') print( ' ___________________________________________________________') def create_report(): # 1234567890123456789012345 $12345678901 1234567890 $123456789012 print('\nREPORT :\n') print(' Donor Name | Total Given | Num Gifts | Average Gift') print(' -----------------------------------------------------------------') for i in range(len(donors[0])): total_given = sum(item for item in donors[1][i]) num_gifts = len(donors[1][i]) avg_gift = total_given/num_gifts print(f' {donors[0][i]:<25} ${total_given:>11.2f} {num_gifts:>10d} ${avg_gift:>12.2f}') if __name__ == "__main__": print('\n Choose one of the following options:') print(' 1 - Send a Thank You ') print(' 2 - Create a Report ') print(' 3 - Quit ') opt = input(' > ') while opt not in ['1','2','3']: opt = input(" Please choose option '1', '2', or '3' > ") if opt == '1': send_thank_you() elif opt == '2': create_report() elif opt == '3': print('Quitting...')
9901e5006e14e1d21529996686db6dc7dd349cd5
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Nick_Lenssen/lesson09/donor_models.py
3,373
3.609375
4
import pathlib class Donor: def __init__(self, full_name): self.name = full_name self.donations = [] @property def total_donation(self): """sum of donation history property""" return sum(self.donations) @property def num_donation(self): """number of donations with a donors history""" return len(self.donations) @property def ave_donation(self): """average donation of a donor's history""" if self.num_donation == 0: return 0 else: return (self.total_donation/self.num_donation) def add_donation(self, *args): """add donation amount to a donor object""" for i in args: self.donations.append(i) def __lt__(self, other): """sorts the order""" return self.total_donation < other.total_donation def __repr__(self): return self.name def send_thank_you(self, money_amount): """Sends a thank you note when a donation is made.""" return "Thank you {} for your donation amount of {} $. We thank you for your support".format(self.name, money_amount) class DonorCollection: """ A class containing information of a list of Donor objects """ def __init__(self, donors=[]): """Create a collection of donor objects.""" self.donor_obs_list = donors @property def list_donors(self): """Return a list of all donors in the collection.""" return self.donor_obs_list @list_donors.setter def list_donors(self, donors = []): self.donor_obs_list.extend(donors) def add_donors(self, *args): """Add a donor to the collection.""" self.list_donors.extend(args) def __repr__(self): names = [donor.name for donor in self.list_donors] return ', '.join(names) def send_thanks_all(self): pth = str(pathlib.Path.cwd())+'/' for this_ob in self.list_donors: mydestin = self.make_mydestin(this_ob.name, pth) #underscore after any part of the name with open(mydestin, "w") as myfile: myfile.write(self.write_thanks_to_all(this_ob.name, this_ob.total_donation)) def make_mydestin(self, name, pth): return pth + name.replace(", ", "_").replace(" ", "_")+".txt" def write_thanks_to_all(self, name, total): my_text = "Dear {},\n\t Thank you for your kind donation of {}\n. It will be put to good use\n\tSincerely\n\t\tThe team"\ .format(name, total) return my_text def create_report(self): """Generate a tabular report of donors in the collection""" report_lines =[] header ='\n{:<19}|{:^13}|{:^13}|{:>13}\n'.format("Donor Name", "Total Given","Num Gifts", "Average Gift") report_lines.append(header) report_lines.append('-'*len(header)) report_lines.append('\n') donor_sort = sorted(self.list_donors, reverse = True) for this_ob in donor_sort: name, num = this_ob.name, this_ob.num_donation total, ave = this_ob.total_donation, this_ob.ave_donation report_str = '{:<19} ${:>13}{:>13} ${:>12,.2f}\n'.format(name, total,num,ave) report_lines.append(report_str) return "".join(report_lines)
0ce8ff95818149a1820c1cecdd983f94931c9489
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/humberto_gonzalez/session05/mailroom.py
3,965
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 17:53:34 2019 @author: humberto gonzalez """ import sys import tempfile import os donor_db = {"Tyrod Taylor": [1000.00, 45.50], "Jarvis Landry": [150.25], "Philip Rivers": [650.23, 40.87, 111.32], "Melvin Gordon": [1677.25, 4300.23, 10532.00], "Mike Williams": [230.56, 12.45, 11.00], "Antonio Brown": [100.00, 88.88] } donors = list(donor_db.keys()) def getKey(item): return item[1] def ordered_db(db): keys = list(db.keys()) temp = [] for name in keys: donation_total = sum(db[name]) temp.append((name,donation_total)) return sorted(temp, key=getKey,reverse=True) main_prompt = "\n".join(("Welcome to the Mailroom!", "Please choose from below options:", "1 - Send a Thank You", "2 - Create a report", "3 - Send letters to all donors", "4 - Exit Program", ">>> ")) def send_thank_you(): '''Prompts user for a donor and donation amount, and then prints out a thank you email''' donor_name = input('What is the full name of the donor you would like to thank? ') if donor_name.lower() == "quit": main() if donor_name not in donors: donor_db[donor_name] = [] try: donation = input('What was the donation amount? ') a = float(donation) except ValueError as e: print('Donation amount needs to be a number, please enter a number') donation = input('What was the donation amount? ') if donation.lower()=="quit": main() donor_db[donor_name].append(float(donation)) print() print() print(f'Dear {donor_name},\n Thank you for your generous donation of ${donation}') def create_report(): '''Creates a report of the current donor database''' print('{:20} | {:^10} | {:^10} | {:^10} |'.format("Donor Name", "Total Given","Num Gifts","Average Gift")) print('-'*64) formatter = "{:20} ${:>10} {:>10} ${:>10}" ordered_donor_db = ordered_db(donor_db) for donor_item in ordered_donor_db: donor_info = donor_item[0] donations = donor_db[donor_info] total = round(sum(donations),2) num = len(donations) average = round(total/num,2) print(formatter.format(donor_info,total,num,average)) def send_letters(): '''Writes and saves letters to all donors in the database in the form of txt files''' formatter = '''Dear {},\n Thank you for your generous donation of ${}. \n Your donation will be put to great use. \n Sincerely, \n -The Organization''' path = tempfile.gettempdir() path = path + "/" + "Letters to Donors" os.mkdir(path) for donor in donor_db: temp = path + "/" + donor.replace(' ','_') + '.txt' with open(temp,'w') as file: txt = formatter.format(donor,donor_db[donor][0]) file.write(txt) file.close() print('Letters have been created and saved to \n a new folder in your temp directory') def exit_program(): print("Bye!") sys.exit() def main(): while True: response = input(main_prompt) # continuously collect user selection # now redirect to feature functions based on the user selection menu_options = {"1":send_thank_you, "2":create_report, "3":send_letters, "4":exit_program} if response not in menu_options: print() print("Please select one of the available options") print("You will be returned to the main menu") main() menu_options.get(response)() if __name__ == "__main__": # don't forget this block to guard against your code running automatically if this module is imported main()
2802d4cbe44623e1cf25251f99dc532c3b1b0f27
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shodges/lesson04/mailroom.py
3,815
3.515625
4
#!/usr/bin/env python3 import tempfile from pathlib import Path from datetime import datetime donors = {'William Henry Harrison' : [806.25, 423.10], 'James K. Polk' : [37.67, 127.65, 1004.29], 'Martin van Buren' : [126.47], 'Millard Fillmore' : [476.21, 2376.21], 'Chester A. Arthur' : [10236.91]} letter_template = """Dear {name}, On behalf of all of us at Save the Marmots, thank you for your recent gift of ${amount:.2f}. When it comes to ensuring marmots have loving homes, every dollar goes a long way. Your very generous gifts of ${total:.2f} will help us provide food and shelter for all of the rescued marmots, and ensure our staff have the resources to train them for placement. Warmest regards, Sean Hodges """ def send_thank_you(): while True: donor = input('Please enter a donor name: ') if donor == 'quit': break elif donor == 'list': for item in donors.keys(): print(item) else: if not donor in donors.keys(): donors[donor] = [] amount = input('Please enter a donation amount: ') try: donors[donor].append(float(amount)) except ValueError: break total = sum(donors[donor]) letter_values = {'name': donor, 'amount': float(amount), 'total': total} print((""" {} """.format(letter_template)).format(**letter_values)) # I'm doing this because I like the extra whitespace when the letter is in-line, otherwise it gets smooshed with the prompts break def generate_report(): print('{:24} | {:10} | {:10} | {:12}'.format('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')) print('-'*68) donor_report = [] # not a ton of value in converting this to a list. it made things a bit more complicated... for donor in donors.keys(): total = sum(donors[donor]) donor_report.append([donor, len(donors[donor]), total]) donor_report.sort(key = lambda x: x[2], reverse = True) # ...for instance here, where sorting the dict with a lambda function in sorted() was still possible, but then I'd have to cast the resultant list back to a dict for item in donor_report: report_output = {'name': item[0], 'total': item[2], 'gifts': item[1], 'average': (item[2] / item[1])} print('{name:24} ${total:10.2f} {gifts:10d} ${average:12.2f}'.format(**report_output)) print('') def save_all_letters(): letter_dir = Path(input('Please specify a directory to save letters in: ')) if not letter_dir.is_dir(): print('{} is an invalid directory; using {}'.format(letter_dir, tempfile.gettempdir())) letter_dir = Path(tempfile.gettempdir()) letter_dir = letter_dir / ('{:%Y%m%d-%H%M}'.format(datetime.now())) try: letter_dir.mkdir(exist_ok=True) except: print('Error creating {}'.format(letter_dir.absolute())) for donor in donors.keys(): total = 0 for amount in donors[donor]: total += amount letter_values = {'name': donor, 'amount': donors[donor][-1], 'total': total} letter = letter_dir / (donor.replace(' ', '_') + '.txt') with letter.open("w") as fileio: fileio.write(letter_template.format(**letter_values)) print('Saved letters in {}'.format(letter_dir.absolute())) if __name__ == '__main__': menu_dispatch = {1: send_thank_you, 2: generate_report, 3:save_all_letters, 4: quit} while True: print("""Mailroom -- Main Menu Options: 1 Send a Thank You 2 Generate a Report 3 Send letters to all donors 4 Quit """) option = input('Please select an option (1, 2, 3, 4): ') if option.isnumeric(): if int(option) in menu_dispatch.keys(): menu_dispatch.get(int(option))()
9cca505939c2e997cf930a06e02bba161c1b90a9
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shumin/lesson01/break.py
174
3.5
4
# NameError y = x + 3 # TypeError A = "3" y = A + 3 # SyntaxError print"This will result in a syntax error") # AttributeError x = "Book" print(x.deletethemiddleletter)
d869b4485e4a2df6cd6432bbd648b3427a0ca317
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Nick_Lenssen/lesson03/strformat_lab.py
913
3.65625
4
#!/usr/bin/env python3 def formatter(my_tup): l = len(my_tup) out_tup = ", ".join(["{:^5}"]*l) return ('the {} numbers are: '+out_tup).format(l, *my_tup) tup = (2,123.4567,10000,12345.67) tup_2 = (1,12,2,3,3333,5,6,12,1,23) list_1 = ['oranges', 1.3, 'lemons', 1.1] print ('file{:>03d} : {:.2f}, {:.2E} , {:.2E}'.format(*tup)) print (f'file00{round(tup[0],2)} : {tup[1]:.2f}, {tup[2]:.2E}, {tup[3]:.2E}') print (formatter(tup)) print ("0{3} {4} {3} 0{0} {1}".format(4, 30, 2017, 2, 27)) print (f'The weight of an {list_1[0].upper()} is {list_1[1]} and the weight of a {list_1[2]} is {list_1[3]*1.2}') table_data = [ ['First', '99.011', 'Second', '88.1'], ['First', '99.000001', 'Second', '88.0011'], ['First', 'b98.5004', 'Second', '88.0001'] ] for row in table_data: print("{} {: >20} {: >20} {: >20}".format(*row)) print ("".join(["{:{width}}"]*10).format(10, *tup_2, width = '5'))
19db572f1e6e1304d43b83ed2cde9ca0845ef36c
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jason_jenkins/lesson04/dict_lab.py
1,895
4.25
4
#!/usr/bin/env python3 """ Lesson 4: dict lab Course: UW PY210 Author: Jason Jenkins """ def dictionaries_1(d): tmp_d = d.copy() print("\nTesting dictionaries_1") tmp_d = dict(name="Chris", city="Seattle", cake="Chocolate") print(tmp_d) tmp_d.pop('city') print(tmp_d) tmp_d.update({'fruit': 'Mango'}) print(tmp_d) print("Keys: ", end='') for v in tmp_d.keys(): print(v, end=', ') print() print("Values: ", end='') for v in tmp_d.values(): print(v, end=', ') print() print(f"Cake is in dictionary: {'cake' in tmp_d.keys()}") print(f"Mango is in dictionary: {'Mango' in tmp_d.values()}") def dictionaries_2(d): tmp_d = d.copy() print("\nTesting dictionaries_2") for k, v in tmp_d.items(): tmp_d[k] = v.lower().count('t') print(tmp_d) def sets_1(): print("\nTesting sets_1") s2 = set() s3 = set() s4 = set() for i in range(21): if(i % 2 == 0): s2.update({i}) if(i % 3 == 0): s3.update({i}) if(i % 4 == 0): s4.update({i}) print(f"Set_2 = {s2}") print(f"Set_3 = {s3}") print(f"Set_4 = {s4}") print(f"Set 3 is a subset of Set 2: {s3.issubset(s2)}") print(f"Set 4 is a subset of Set 2: {s4.issubset(s2)}") def sets_2(): print("\nTesting sets_2") s_python = set() for i in "Python": s_python.update({i}) s_python.update({"i"}) print(s_python) s_maration_frozen = frozenset({"m", "a", "r", "a", "t", "h", "o", "n"}) print(s_maration_frozen) print(f"Union: {s_python.union(s_maration_frozen)}") print(f"Intersection: {s_python.intersection(s_maration_frozen)}") if __name__ == "__main__": # Create a list d = dict(name="Chris", city="Seattle", cake="Chocolate") dictionaries_1(d) dictionaries_2(d) sets_1() sets_2()