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
d282841fed0820e370bb96a7934b4d7fd3a24471
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/N0vA/lesson_04/dict_lab.py
1,264
3.765625
4
#!/usr/bin/env python3 # Make dictionary as provide dict_1 = dict(name='Chris', city='Seattle', cake='chocolate') print(dict_1) # Delete cake entry dict_1.pop('cake') print(dict_1) # Add fruit -- Mango dict_1['fruit'] = 'Mango' print(dict_1) # Display dictionary keys print(dict_1.keys()) # Print dictionary values print(dict_1.values()) # Display of cake is a key key in the dictionary 'cake' in dict_1 # Display whether Mango is a value in the dictionary 'Mango' in dict_1.values() # Create a dictionary from dict_1 based on 't's in each value dict_2 = dict(name='Chris', city='Seattle', cake='chocolate') for k,v in dict_2.items(): dict_2[k] = v.count('t') print(dict_2) # Sets - s2, s3, s4 of numbers from 0-20 divisible by that number s2 = set() s3 = set() s4 = set() for i in range(21): if i % 2 == 0: s2.add(i) if i % 3 == 0: s3.add(i) if i % 4 == 0: s4.add(i) print(s2) print(s3) print(s4) print(s3.issubset(s2)) print(s4.issubset(s2)) # Make set with letters from 'Python' and add 'i' to it p = {'P', 'y', 't', 'h', 'o', 'n'} p.add('i') print(p) # Create frozenset with 'marathon' m = frozenset({'m', 'a', 'r', 'a', 't', 'h', 'o', 'n'}) union = p.union(m) print(union) inter = p.intersection(m)
1640c7c6bef63b63e994f28ffa5cad1bbd2a36b7
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/phrost/Lesson03/Exercises/Series_3.py
478
3.9375
4
fruit_upper = ['Apples', 'Pears', 'Oranges', 'Peaches'] fruit_lower = [fruit.lower() for fruit in fruit_upper] fruit_copy = list(fruit_lower) for fruit in fruit_lower: while True: fruit_v = input(f'do you like {fruit}: ') if fruit_v.lower() == 'yes': break elif fruit_v.lower() == 'no': fruit_copy.remove(fruit) break else: print(f'please say yes or no do you like {fruit}: ') print(fruit_copy)
bc1fe51df6dabcadf392317ac91e359f7e565e48
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kimc05/Lesson08/circle.py
1,443
4.4375
4
""" Christine Kim Lesson 8 Assignment Circles """ import math class Circle(): #initiate circle with radius def __init__(self, radius): self.radius = radius def __str__(self): return "Circle with radius: {}".format(self.radius) def __repr__(self): return "Circle({})".format(self.radius) def __add__(self, other): return Circle(self.radius + other.radius) def __mul__(self, other): return Circle(self.radius * other) def __radd__(self, other): return self.__add__(other) def __lt__(self, other): return (self.radius, self.diameter, self.area) < (other.radius, other.diameter, other.area) def __eq__(self, other): return (self.radius, self.diameter, self.area) == (other.radius, other.diameter, other.area) def __le__(self, other): return (self.radius, self.diameter, self.area) <= (other.radius, other.diameter, other.area) def __rmul__(self, other): return Circle(self.radius * other) def __truediv__(self, other): return Circle(self.radius / other.radius) @property def diameter(self): return self.radius * 2 @diameter.setter def diameter(self, diameter): self.radius = diameter / 2 @property def area(self): return math.pi * (self.radius ** 2) @classmethod def from_diameter(c, diameter): self = c(diameter / 2) return self
1ca373999a0bf0ed7da537d07483c221cbe53721
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/steve_walker/lesson03/mailroom.py
3,157
3.984375
4
#!/usr/bin/env python3 import sys # Hard coded donor records donor_records = [("Rhianna", [747, 3030303, 1968950]), ("Grumps", [5.99]), ("EatPraySlay", [100000,200000, 300000]), ("Muir", [469503, 50000, 186409]), ("Spacewalker", [4406, 342])] # Store new donation record, then create e-mail to thank donor def thank_donor(): while True: donor_name = input("Who would you like to thank? " "(Type 'list' to see a list of donors.)\n Full Name: ") entry_exists = False # Print list of existing donors to choose from if donor_name.lower() == "list": entry_exists = True for i in donor_records: print(i[0]) # Locate the record for the donor entered, then get and store # the donation amount else: for i in donor_records: if donor_name.lower() == i[0].lower(): entry_exists = True donation_amount = float(input( "Please enter the donation amount: ")) i[1].append(donation_amount) # If this is a new donor, collect and store the donor info if entry_exists == False: donation_amount = float(input(f"Adding {donor_name} to " "the database.\nPlease enter the donation amount: ")) donor_records.append([donor_name, [donation_amount]]) # Generate the thank you e-mail print(f"To the esteemed {donor_name}:\n\n" "Thank you for generous donation of " f"${donation_amount:.2f}. You're a champion!") # Return donor records return(donor_records) # Create a report of all donor records to date def create_report(): # Set up column headers print(" "+"-"*60+"\n Donor Name"+" "*10+ "| Total Given | Num Gifts | Average Gift\n "+"-"*60) # Generate and print donor summaries donor_summary = [] for record in donor_records: donor_summary.append([record[0], sum(record[1],0), len(record[1]), sum(record[1],0)/len(record[1])]) donor_summary.sort(key = lambda donor_summary: donor_summary[1], reverse = True) for i in donor_summary: print(" {0:<20} ${1:>11.2f}{2:>12} ${3:>12.2f}".format(*i)) # Display a user menu, then act on the user's selection def main(): # Let the user choose what to do, then call the function to make it # happen and repeat until the user quits while True: user_action = input("\n".join(("\nWhat would you like to do?", " Enter 1 to Send a Thank You", " Enter 2 to Create a Report", " Enter q to quit.", " >>>"))) if user_action == "1": thank_donor() elif user_action == "2": create_report() elif user_action[0].lower() == "q": print("\nThanks for playing!") sys.exit() else: print("Let's behave. Try again using one of the options!") if __name__ == "__main__": main()
ec8f871bad690fa1354b2adb8c811d6cc2efc1ba
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/scott_bromley/lesson03/slicing.py
2,775
4.09375
4
#!/usr/bin/env python3 # Write some functions that take a sequence as an argument, and return a copy of that sequence: # (1) with the first and last items exchanged. # (2) with every other item removed. # (3) with the first 4 and the last 4 items removed, and then every other item in between. # (4) with the elements reversed (just with slicing). # (5) with the middle third, then last third, then the first third in the new order. def main(): # exchange_first_last tests assert exchange_first_last((1, 2, 5, 7, 0)) == (0, 2, 5, 7, 1) assert exchange_first_last(['ball', 0, 2.5, 'glove', (1, 2, 3)]) == [(1, 2, 3), 0, 2.5, 'glove', 'ball'] assert exchange_first_last('this is a string') == "ghis is a strint" # remove_every_other tests assert remove_every_other((1, 2, 5, 7, 0)) == (1, 5, 0) assert remove_every_other(['ball', 0, 2.5, 'glove', (1, 2, 3)]) == ['ball', 2.5, (1, 2, 3)] assert remove_every_other('this is a string') == 'ti sasrn' # first_four_last_four tests assert first_four_last_four((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) == (5,) assert first_four_last_four(['ball', 0, 2.5, 'glove', (1, 2, 3)]) == [] assert first_four_last_four("this is a string") == ' sas' # reverse tests assert reverse([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] assert reverse((2.5, 'ball', 'glove', 0, (1, 2, 3))) == ((1, 2, 3), 0, 'glove', 'ball', 2.5) assert reverse("this is a string") == 'gnirts a si siht' # middle_last_first_third tests assert middle_last_first_third((1, 2, 3, 4, 5, 6, 7, 8, 9)) == (4, 5, 6, 7, 8, 9, 1, 2, 3) assert middle_last_first_third("this is a string") == "is a stringthis " assert middle_last_first_third((2, 54, 13, 12, 5, 32)) == (13, 12, 5, 32, 2, 54) def exchange_first_last(seq): ''' :param seq: a sequence :return: sequence w/ first and last items swapped ''' seq_list = seq[1:-1] return seq[-1:] + seq_list + seq[:1] def remove_every_other(seq): ''' :param seq: a sequence :return: sequence w/ every other item removed ''' return seq[::2] def first_four_last_four(seq): ''' :param seq: a sequence :return: sequence w/ first four and last four elements removed and every other item thereafter ''' return seq[4:-4:2] def reverse(seq): ''' :param seq: a sequence :return: sequence w/ elements reversed ''' return seq[::-1] def middle_last_first_third(seq): ''' :param seq: a sequence :return: sequence w/ middle third, last third, first third ''' return seq[len(seq) // 3:] + seq[0:len(seq) // 3] if __name__ == "__main__": print("Running", __file__) main() else: print("Running %s as imported module", __file__)
2f7f02ab81d60c8175980069e2a805b72e1b9f54
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/humberto_gonzalez/Lesson2/fizzBuzz.py
325
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 6 18:28:56 2019 @author: humberto gonzalez """ def fizzBuzz(n): if n%5==0 and n%3==0: print('FizzBuzz') elif n%3==0: print('Fizz') elif n%5==0: print('Buzz') else: print(str(n)) for i in range(101): fizzBuzz(i)
52ca43978d8ddd88d5ea955e0618435a126b96f3
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/alexander_boone/lesson03/exercises/slicing.py
2,387
4.0625
4
# define exchange_first_last def exchange_first_last(seq): """Exchange the first and last items of a sequence.""" return seq[-1:] + seq[1:-1] + seq[:1] # define remove_every_other def remove_every_other(seq): """Remove every other item in a sequence.""" return seq[::2] # define remove_end_fours def remove_end_fours(seq): """Remove the first and last four items of the sequence and return every other item of remaining sequence""" return seq[4:-4:2] # define reverse_seq def reverse_seq(seq): """Reverse the elements in a sequence.""" return seq[::-1] # define reorder_seq_thirds def reorder_seq_thirds(seq): """Reorder a sequence into last third, first third, then middle third.""" l = len(seq) # check seq length if l % 3 != 0: raise Exception('The input sequence length should be divisible by 3. The input length was: {}'.format(l)) third = int(l/3) return seq[-third:] + seq[:third] + seq[third:-third] # test all functions if __name__ == "__main__": # test variables a_string = "Monty Python" a_list = ["M", "o", "n", "t", "y"] a_long_string = "One more step closer to writing LeetCode" a_long_list = ["all", "i", "do", "is", "code", "code", "code", "no", "matter", "what", "got", "coding", "on", "my", "mind", "I", "can", "never", "get", "enough"] num_string = "123456789" num_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9) # exchange_first_last assert exchange_first_last(a_string) == "nonty PythoM" assert exchange_first_last(a_list) == ["y", "o", "n", "t", "M"] print('exchange_first_last: Success!') # remove_every_other assert remove_every_other(a_string) == "MnyPto" assert remove_every_other(a_list) == ["M", "n", "y"] print('remove_every_other: Success!') # remove_end_fours assert remove_end_fours(a_long_string) == "mr tpcoe owiigLe" assert remove_end_fours(a_long_list) == ["code", "code", "matter", "got", "on", "mind"] print('remove_end_fours: Success!') # reverse_seq assert reverse_seq(a_string) == "nohtyP ytnoM" assert reverse_seq(a_list) == ["y", "t", "n", "o", "M"] print('reverse_seq: Success!') # reorder_seq_thirds assert reorder_seq_thirds(num_string) == "789123456" assert reorder_seq_thirds(num_tuple) == (7, 8, 9, 1, 2, 3, 4, 5, 6) print('reorder_seq_thirds: Success!')
4007145b5121825c67d73f3bbef5a9ceab1f8d42
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jacob_daylong/Lesson 3/MailRoom/mailroom.py
3,330
3.953125
4
 #Write a small command-line script called mailroom.py. This script should be executable. The script should accomplish the following goals: #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”. from operator import itemgetter, attrgetter total_given = 0.00 full_name = '' num_gifts = 0 table_header = ['Donor Name', 'Total Given', 'Num Gifts', 'Average Gift'] donor_table = [['Jane Doe', 10000, 4000, 2000], ['John Doe', 10000, 2000, 5000, 3000], ['Bobby Newport', 2000, 100], ['Johnny Mnemonic', 900, 800, 1000], ['Phillip Dick', 2220]] def menu(): print() print("Please choose an option:") print("1. Send a Thank You") print("2. Create a Report") print("3. Quit") print() def send_thankyou(full_name): print() while full_name == '': full_name = input("Please enter Donor's Full Name: ") if full_name == "list": print() print('|{:<{width}s}|'.format(*table_header, width=20)) for row in donor_table: print('|{:<{width}s}|'.format(*row, width=20)) elif full_name == 'quit': break else: for row in donor_table: if full_name.lower() == row[0].lower(): amt_given = input("Please enter Donor's gift amount: ") row.append(int(amt_given)) mail_text = "Dear {}, \nThank you for your donation of ${}. \nSincerely, Jake".format(row[0], amt_given) print(mail_text) break if full_name != row[0] and full_name.lower() != "list": donor_table.append([full_name]) amt_given = input("Please enter Donor's gift amount: ") donor_table[-1].append(int(amt_given)) mail_text = "Dear {}, \nThank you for your donation of ${}. \nSincerely, Jake".format(donor_table[-1][0], amt_given) print(mail_text) def donor_sort_key(entry): return sum(donor_table.get(entry)) def create_report(table_header, donor_table): print() print('|{:<{width}s}|{:<{width}s}|{:<{width}s}|{:<{width}s}|'.format(*table_header, width = 20)) print('-------------------------------------------------------------------------------------') SortedDonors = sorted(donor_table, key=donor_sort_key, reverse=True) for row in SortedDonors: donor_total = sum(row[1:]) donation_avg = donor_total/(len(row)-1) donation_qty = len(row)-1 print('|{:<{width}s}|${:<19.2f}|{:<{width}d}|${:<19.2f}|'.format(row[0], donor_total, donation_qty, donation_avg, width = 20)) def main(): while True: menu() user_input = input("Choice Selected: ") if user_input == '1': send_thankyou(full_name) elif user_input == '2': create_report(table_header, donor_table) elif user_input == '3': break if __name__ == "__main__": main()
68163531259e1ec3f8bc2838f873060c9e412207
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/annguan/lesson05/mailroom3.py
4,348
3.71875
4
#!/usr/bin/env python3 ### Lesson 5 Mailroom, Part 3, Add Exceptions and Use Comprehensions from textwrap import dedent import os import sys import math # a data structure holds a list of donors and a history of the amounts they have donated. def get_donor_db(): return {'Abraham Lincoln': ("Abraham Lincoln", [145674.32, 23465]), 'Barack Obama': ("Barack Obama", [3456324.11, 3495, 323]), 'Charlie Brown':("Charlie Brown",[453.67]), 'Doctor Who': ("Doctor Who", [5600, 42]), 'Eve WallE': ("Eve WallE",[2.22]) } OUT_PATH = "thank_you_letters" def ready_run (): if not os.path.isdir(OUT_PATH): os.mkdir(OUT_PATH) # Write thank you letters to disk as a text file def write_letters_disk(): for donor in donor_db.values(): letter = comp_letter(donor) filename = donor[0].replace(" ", "_") + ".txt" print("writing letter to:", donor[0]) filename = os.path.join(OUT_PATH, filename) with open(filename, 'w') as file: file.write(letter) # prompt user to choose from a menu of 4 actions: "send letters to all", Send a Thank you", "Create a Report", or "quit" def menu_selection(): action = input(dedent(''' Choose an action: 1 - Send letters to all 2 - Send a Thank You 3 - Create a Report 4 - Quit >''')) return action.strip() # Thank You Letter Composition def comp_letter(donor): return dedent('''Dear {0:s}, Thank you for your donation of ${1:.2f}. See you soon. '''.format(donor[0], donor[1][-1])) #Validate donation inputs by user def receive_donation(name): while True: donation_amount = input ("Enter a donation amount or Menu to exit > ").strip() if donation_amount == "menu": return try: amount = float(donation_amount) if math.isnan(amount) or math.isinf(amount) or round(amount, 2) == 0.00: raise ValueError except ValueError: print("invalid donation amount\n") else: break donor = find_donor(name) if donor is None: donor = add_donor(name) donor[1].append(amount) print(comp_letter(donor)) # Sending a Thank You def add_donor(name): name = name.strip() donor = (name,[]) donor_db[name.lower()] = donor return donor def find_donor(name): key = name.strip().lower() return donor_db.get(key) def list_donors(): l1 = ["Donor List:"] for donor in donor_db.values(): l1.append(donor[0]) return "\n".join(l1) def send_thank_you(): while True: name = input ("Enter the donor's name " "or 'list' to see all donors or 'menu' to exit)> ").strip() if name == "list": print(list_donors()) elif name == "menu": return else: receive_donation(name) # Create a Report def sort_key(item): return item[1] def create_donor_report(): report_lines = [] for name,donation in donor_db.values(): total_donation = sum(donation) num_donation = len(donation) avg_donation = total_donation/num_donation report_lines.append((name,total_donation,num_donation,avg_donation)) report_lines.sort(key=sort_key) report = [] report.append("{:25s} | {:11s} | {:9s} | {:12s}".format("Donor Name", "Total Donation", "Num Donation", "Average Donation")) report.append("-" * 70) for line in report_lines: report.append("{:25s} ${:11.2f} {:9d} ${:20.2f}".format(*line)) return "\n".join(report) def print_donor_report(): print(create_donor_report()) def quit(): sys.exit(0) # main interaction if __name__ == "__main__": ready_run() donor_db = get_donor_db() selection_dict = {"1": write_letters_disk, "2": send_thank_you, "3": print_donor_report, "4": quit } while True: selection = menu_selection() try: selection_dict[selection]() except KeyError: print("invalid selection")
b7ff5f7e293523f6c6c07b9b4d6f0180d16f5dfe
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/thomasvad/lesson3/listlab.py
1,997
4.09375
4
#series 1 #fruit list fruits = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruits, '\n') # Adding respondent input to list response = input('What fruit do you want to add? ') fruits.append(response.capitalize()) print(fruits, '\n') # returning number and fruit in list fruitlen = len(fruits) response2 = input('PLease pick a number from 1 to {}: '.format(fruitlen)) print('{} is item {} on the fruit list'.format(fruits[int(response2)-1], response2), '\n') # adding 2 fruits to the list print('Adding Mangos and Blueberries:') fruits = ['Mangos'] + fruits print(fruits, '\n') fruits.insert(0, 'Blueberries') print(fruits, '\n') # printing all fruits that start with p print('They start with p:') for fruit in fruits: lcaseI = fruit.lower() if lcaseI.startswith('p'): print(fruit) print('\n') #series2 print('removing the last fruit:') print(fruits) fruits.pop(-1) print(fruits, '\n') # asking what they want to remmove, checking if it is in the list then removing if it is there lowerfruits = [lfruit.lower() for lfruit in fruits] response2 = input('What fruit would you like to delete? ') print('\n') while response2.lower() not in lowerfruits: print(fruits) response2 = input('What fruit would you like to delete? Please pick one from the list above. ') else: for fruit in fruits: if fruit.lower() == response2.lower(): fruits.remove(fruit) print(fruits, '\n') #series3 # going through the fruit list and deleting any fruits they dont like ans = ['yes', 'no'] for fruit in fruits[::-1]: response3 = input('Do you like {}? '.format(fruit)) while response3.lower() not in ans: response3 = input('Do you like {}? Please type yes or no. '.format(fruit)) if response3.lower() == 'no': fruits.remove(fruit) print(fruits, '\n') #series4 print('new list and original', '\n') fruits = ['Apples', 'Pears', 'Oranges', 'Peaches'] newlist = [fruit[::-1] for fruit in fruits] print(newlist) fruits.pop() print(fruits)
21b19da299776cc9a20ca787c6f8a7b2f48f6f36
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mattcasari/lesson04/trigrams.py
9,265
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Lesson 4, Exercise 2 @author: Matt Casari Link: https://uwpce-pythoncert.github.io/PythonCertDevel/exercises/kata_fourteen.html """ import sys import string import random import textwrap from pprint import pprint BOOK_START_STR = "*** START OF THIS PROJECT GUTENBERG EBOOK" BOOK_END_STR = "*** END OF THIS PROJECT GUTENBERG EBOOK " # Change to True to save a file called temp.txt WRITE_TO_FILE = False def build_trigrams_old(words): """ build up the trigrams dict from the list of words returns a dict with: keys: word pairs values: list of followers """ trigrams = {} num_words = len(words) - 1 for i in range(len(words) - 2): pair = tuple(words[i : i + 2]) follower = words[i + 2] trigrams.setdefault(pair, []) trigrams[pair].append(follower) return trigrams def find_start_of_text(in_data, start_str=""): """ Finds the start string in a block of text and returns the index of the text remaining. Args: in_data: String to search through start_str: String to search for (Case Sensitive!) Returns: Index of text remaining after start string or None """ idx = in_data.find(start_str) if idx == -1: return None else: return idx def find_end_of_text(in_data, end_str=""): """ Finds the end string in a block of text and returns the index of the text remaining. Args: in_data: String to search through end_str: String to search for (Case Sensitive!) Returns: Index of text remaining after start string or None """ idx = in_data.find(end_str) if idx == -1: return None else: return idx def format_text(lines): """ Remove punctuation and lowercase all words except for special cases. Args: lines: text lines to format. Returns: data: formatted text """ data = [] for line in lines.split(): line = line.rstrip() # line = line.translate( # str.maketrans(string.punctuation, " " * len(string.punctuation)) # ) line = remove_punctuation(line) line = remove_capitalization(line) if line: data.append(" ".join(line.split())) data = " ".join(data) data = data.replace(" ", " ") return data def remove_punctuation(line): """ Remove punctuation, but leave apostrophes for contraction words. Args: line: Text to remove punctuation from. Return: line: Formatted text with punctuation removed """ punctuation = '/:;~=+_*&^%$#@!?.,-()"' translation = line.maketrans(punctuation, " " * len(punctuation)) line = line.translate(translation) line2 = line.split() result = [] for l in line2: if l[0] == "'" or l[-1] == "'": if len(l) > 1: if l[0] == "'": l = l[1:] elif l[-1] == "'": l = l[:-1] else: l = [] result.append(l) else: result.append(l) line = " ".join(result) return line def read_in_data(filename, start_str="", end_str=""): """ Read in text from a file. Looks for start string and returns all text after with punctuation removed and lower case (except for I). Args: filename: Name of file to read in (with file extension) start_str: String which indicates start of actual text. Returns: Formatted text stripped from file """ lines = [] with open(filename, "r+") as infile: text = "".join(infile.readlines()) return format_text(text) def remove_capitalization(in_data): """ Removes capitalization from string except for "I". Args: in_data: string to convert to lower case. Returns: Formatted string ToDo: Add ability to keep proper nouns capitalized. """ return_data = [] for data in in_data.split(" "): data = data.lower() if len(data) == 1: if data == "i": data = data.capitalize() if len(data) > 1: if data[0] == "i" and data[1] == "'": data = data.capitalize() return_data.extend("".join(data)) return_data += " " return "".join(return_data[:-1]) def make_words(in_data): """ Split string into words. Args: in_data: string to split Returns: String split into words """ words = in_data.split(" ") return words def build_trigrams(words): """ Creates the trigram keyword pairs and values. Args: words: List of words in text Returns: trigrams: All trigram keyword pairs and values in tuple format """ trigrams = {} num_words = len(words) - 1 for i in range(len(words) - 2): pair = tuple(words[i : i + 2]) follower = words[i + 2] trigrams.setdefault(pair, []) trigrams[pair].append(follower) return trigrams def build_text(word_pairs, num_paragraphs=40): """ Build new text based on trigram word pairs. Creates text with assumption of Args: word_pairs: trigram keyword pair tuples to generate text with num_paragraphs: Return: output_text: Newly generated random text """ output_text = ["\t"] for idx in range(num_paragraphs): # Start of Paragraph paragraph = [] paragraph_length = random.randint(3, 8) for sentence_cnt in range(paragraph_length): # Start of sentence sentence_length = random.randint(15, 20) sentence = [] for word_cnt in range(sentence_length): # Start of word word = [] if word_cnt == 0: word_pair = random.choice(list(word_pairs.keys())) sentence.append(word_pair[0]) sentence.append(word_pair[1]) else: word_pair = tuple(sentence[-2:]) word_pair = word_pairs[word_pair] if not word_pair: break sentence.append(random.choice(list(word_pair))) sentence = " ".join(sentence) sentence = sentence[0].upper() + sentence[1:] sentence += "." paragraph.append(sentence) temp = " ".join(paragraph) temp = textwrap.wrap(temp) output_text.append("\n".join(paragraph)) output_text = "\n\n\t".join(output_text) return "".join(output_text) if __name__ == "__main__": # Test Find Start String test_str = "I once found a shell\n *** Story Start\n Gooble Gobble says the Turkey" start_str1 = "*** Story Start" start_str2 = "*** story start" assert 22 == find_start_of_text(test_str, start_str1) assert None == find_start_of_text(test_str, start_str2) # Test Find End String test_str = "The end of the story\n proved to be too much\n for the young child.\n *** End of Story" end_str1 = "*** End of Story" end_str2 = "!!! this is the end" assert 67 == find_end_of_text(test_str, end_str1) assert None == find_end_of_text(test_str, end_str2) # Test Remove Capitalization Function test_str = "The story of how I wrote this program" remove_cap_string = remove_capitalization(test_str) assert "the story of how I wrote this program" == remove_cap_string # Test Format Text function test_str = "Welcome to another - chance to test my func() code!" formatted_str = format_text(test_str) assert "welcome to another chance to test my func code" == formatted_str # Test Format Text Function does not change I's test_str = "I suspect that I did not Identify all of my bugs" formatted_str = format_text(test_str) assert "I suspect that I did not identify all of my bugs" == formatted_str # Test Format Text function with apostrophes test_str = "He said 'Hello, this is Sam's' and left" formatted_str = format_text(test_str) assert "he said hello this is sam's and left" == formatted_str # Test Make Words test_str = "one two three four five" make_words_words = make_words(test_str) assert ["one", "two", "three", "four", "five"] == make_words_words # Test build_trigrams test_words = "I wish I may I wish I might".split() build_tri_response = build_trigrams(test_words) tri_expected = { ("I", "may"): ["I"], ("I", "wish"): ["I", "I"], ("may", "I"): ["wish"], ("wish", "I"): ["may", "might"], } assert tri_expected == build_tri_response # Run main program to generate new text try: filename = sys.argv[1] except IndexError: print("You must pass in a filename") sys.exit(1) in_data = read_in_data(filename, BOOK_START_STR, BOOK_END_STR) words = make_words(in_data) word_pairs = build_trigrams(words) new_text = build_text(word_pairs) print(new_text) if WRITE_TO_FILE: with open("temp.txt", "w") as f: f.write(new_text)
f2b721313e23b99aea53565563efd9b5373e0883
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/karl_perez/lesson03/list_lab.py
2,968
4.25
4
#!/usr/bin/env python3 """Series 1""" #Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”. list_original = ['Apples', 'Pears', 'Oranges', 'Peaches'] series1 = list_original[:] #Display the list (plain old print() is fine…). print(series1) #Ask the user for another fruit and add it to the end of the list. user = input('Add another fruit please:\n') series1.append(user) #Display the list. print(series1) #Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). Remember that Python uses zero-based indexing, so you will need to correct. num = input('Please give a number. ') integ_num = int(num) print(integ_num, series1[integ_num-1]) #Add another fruit to the beginning of the list using “+” and display the list. series1 = ['Grapes'] + series1 print(series1) #Add another fruit to the beginning of the list using insert() and display the list. series1.insert(0,'Bananas') print(series1) #Display all the fruits that begin with “P”, using a for loop. fruits_p = [] for i in series1: if i[0] == 'P': fruits_p.append(i) print("Display all the fruits that begin with 'P': {}".format(fruits_p)) """Series 2""" #Display the list. print(list_original) series2 = list_original[:] #Remove the last fruit from the list. series2.pop() #Display the list. print(series2) #Ask the user for a fruit to delete, find it and delete it. user_1 = input("Pick a fruit to remove please: ") if user_1 not in series2: print("Please choose a fruit from the list.") else: series2.remove(user_1) print(series2) #(Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.) series2 = series2 * 2 print("multipling the list by 2:") print(series2) user_2 = input("Enter another fruit to remove please: ") while user_2 in series2: series2.remove(user_2) print(series2) # """Series 3""" series3 = list_original[:] #Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list (making the fruit all lowercase). for fruits in series3[:]: user_3 = input("Do you like" + " " + fruits + "?\n") #For each “no”, delete that fruit from the list. if user_3 == 'no': series3.remove(fruits) elif user_3 == 'yes': continue #For any answer that is not “yes” or “no”, prompt the user to answer with one of those two values else: print("Please answer with either 'yes' or 'no'") #Display the list. print(series3) """Series 4""" series4 = list_original[:] new_series_list = [] #Make a new list with the contents of the original, but with all the letters in each item reversed. for fruit in series4: new_series_list.append(fruit[::-1]) print(new_series_list) #Delete the last item of the original list. del list_original[-1] #Display the original list and the copy. print(list_original)
3c91c177004d04b82afa1f90dc80fb41ddafb52f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/IanMayther/Lesson04/dict_lab.py
1,078
3.84375
4
#!/usr/bin/env python3 #Dictionaries 1 person = dict({('name','Chris'),('city','Seattle'),('cake','Chocolate')}) print(person) del person['cake'] print(person) person.update({'fruit': 'Mango'}) print(person.keys()) print(person.values()) #Dictionaries 2 #return to original del person['fruit'] person.update({'cake': "Chocolate"}) #count 't's def count_t(string): return int(string.count('t')) people = dict({}) for key in person.keys(): people[key] = count_t(person[key]) print(people) #Sets 1 #Initialize sets s2 = set() s3 = set() s4 = set() #Populate sets for i in range(21): if i % 2 == 0: s2.add(i) if i % 3 == 0: s3.add(i) if i % 4 == 0: s4.add(i) #Display sets print(s2) print(s3) print(s4) #Confirm sub-sets print(f"Is s3 a subset of s2? {s2.issuperset(s3)}") print(f"Is s4 a subset of s2? {s2.issuperset(s4)}") #Sets 2 p = set('python') m = frozenset('marathon') p.add('i') u = p.union(m) inter = p.intersection(m) print(f"P = {p}") print(f"M = {m}") print(f"Union = {u}") print(f"Intersection = {inter}")
fba4bb1f6f02ab6e38ce783d943fe19719145a12
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/rfelts/lesson08/test_circle_pytest.py
3,979
4.125
4
#!/usr/bin/env python3 # Russell Felts # Assignment 8 - Circle Class Unit Tests import pytest import math from circle_class import Circle from circle_class import Sphere def test_init_circle(): """ Test that a circle can be initialized """ circle = Circle(7) assert circle.radius == 7 def test_get_circle_diameter(): """ Test getting the diameter property """ circle = Circle(5) assert circle.diameter == 5 * 2 def test_set_circle_diameter(): """ Test the diameter can be set and it updates the radius """ circle = Circle(2) assert circle.radius == 2 assert circle.diameter == 2 * 2 circle.diameter = 5 assert circle.diameter == 5 assert circle.diameter == circle.radius * 2 def test_get_circle_area(): """ Test getting the area """ circle = Circle(6) assert circle.area == math.pi * 6 ** 2 def test_set_circle_area(): """ Verify the area can not be set """ circle = Circle(3) with pytest.raises(AttributeError): circle.area = 4 def test_creation_circle_diameter(): """ Test a Circle can be created using the diameter property """ circle = Circle.from_diameter(6) assert circle.radius == 3 def test_circle_str(): """ Verify the string printed is correct """ circle = Circle(8) assert str(circle) == "Circle with radius: 8" def test_circle_repr(): """ Verify the output from repr is the expected value """ circle = Circle(2) assert repr(circle) == "Circle(2)" def test_circle_add(): """ Test adding two circles together """ c1 = Circle(2) c2 = Circle(3) c3 = c1 + c2 assert c3.radius == 5 def test_circle_multiply(): """ Test a circle can be multiplied by a number """ c1 = Circle(2) c2 = c1 * 2 assert c2.radius == 4 c3 = 2 * c1 assert c3.radius == 4 def test_circle_comparison(): """ Test greater than, less than, equals """ c1 = Circle(2) c2 = Circle(3) assert c2 > c1 assert c1 < c2 assert (c1 > c2) is False assert c1 < Circle(4) assert Circle(5) > Circle(1) assert Circle(3) == c2 assert Circle(5) != c2 assert (Circle(5) == c2) is False def test_circle_sort(): circle_list = [Circle(6), Circle(7), Circle(8), Circle(4), Circle(0), Circle(2), Circle(3), Circle(5), Circle(9), Circle(1)] print(circle_list) circle_list.sort() assert circle_list == [Circle(0), Circle(1), Circle(2), Circle(3), Circle(4), Circle(5), Circle(6), Circle(7), Circle(8), Circle(9)] def test_sphere_init(): """ Test that a sphere can be initialized """ sphere = Sphere(2) assert sphere.radius == 2 assert sphere.diameter == 2 * 2 def test_sphere_str(): """ Verify the string printed is correct """ sphere = Sphere(8) assert str(sphere) == "Sphere with radius: 8" def test_sphere_repr(): """ Verify the output from repr is the expected value """ sphere = Sphere(2) assert repr(sphere) == "Sphere(2)" def test_get_sphere_area(): """ Test getting the area """ sphere = Sphere(6) assert sphere.area == 4 * math.pi * 6 ** 2 def test_set_sphere_area(): """ Verify the area can not be set """ sphere = Sphere(3) with pytest.raises(AttributeError): sphere.area = 4 def test_get_sphere_volume(): """ Test getting the area """ sphere = Sphere(6) assert sphere.volume == (4/30) * math.pi * 6 ** 3 def test_set_sphere_volume(): """ Verify the area can not be set """ sphere = Sphere(3) with pytest.raises(AttributeError): sphere.volume = 4 def test_creation_sphere_diameter(): """ Test a Sphere can be created using the diameter property """ sphere = Sphere.from_diameter(6) assert str(sphere) == "Sphere with radius: 3.0" assert sphere.radius == 3 assert sphere.diameter == 6 assert sphere.volume == (4/30) * math.pi * 3 ** 3 assert sphere.area == 4 * math.pi * 3 ** 2
a5a1f4db84ae2a0601fec667d9c942fbd7ee7fd1
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Jaidjen/lesson03/list_lab.py
1,485
4.03125
4
#Series 1 Fruits=["Apples", "Pears", "Oranges", "Peaches"] print(Fruits) New_Fruit=input('Please add another fruit to the list: ') Fruits.append(str(New_Fruit)) print(Fruits) User_input=int(input('Please choose a fruit by providing a number: ')) if User_input < 1: print("Pleasa pick a number greater than zero") else: print("You choose:", User_input, Fruits[User_input-1]) addFruit = "Coconut" Fruits= [addFruit]+Fruits print(Fruits) Fruits.insert(0,'Kiwi') print(Fruits) for fruit in Fruits: if fruit.startswith('P'): print(fruit) #Series 2 print(Fruits) del Fruits[-1] print(Fruits) a =input('Which fruit do you want to delete: ') if a in Fruits: Fruits.remove(a) else: print(a,"cannot be deleted because it is not on the list") print(Fruits) #Series 3 def user_input_list(): index = 0 while index <= len(Fruits): #for i in range(len(Fruits)): #while True: for i, fruits in enumerate(Fruits): #for i in Fruits: fruitchoice = input('Do you like ' + Fruits[i]+'? yes/no ') if fruitchoice == 'no': del Fruits[i] elif fruitchoice == 'yes': continue else: print("Please answer yes or no only") #break #print(Fruits) user_input_list() print(Fruits) #Series 4 New_Fruit= Fruits.copy() Rev_strings = [x[::-1] for x in New_Fruit][::-1] print(Rev_strings) del Fruits[-1] print(Fruits) print(New_Fruit)
da22a15916a5dc3e1106d278c9eb041dee62fa5e
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/bcoates/lesson01/codebat.py
2,916
3.515625
4
# Warmup-1 def sleep_in(weekday, vacation): if weekday == False or vacation == True: return True else: return False def diff21(n): if n < 21: return abs(n - 21) else: return abs(n - 21) * 2 def parrot_trouble(talking, hour): if talking == True: if hour < 7 or hour > 20: return True else: return False else: return False def makes10(a, b): if a == 10 or b == 10 or (a + b) == 10: return True else: return False def near_hundred(n): if abs(100 - n) <= 10 or abs(200 - n) <= 10: return True else: return False def pos_neg(a, b, negative): if negative == False: if a < 0 and b > 0: return True elif a > 0 and b < 0: return True else: return False else: if a < 0 and b < 0: return True else: return False def not_string(str): if str[:3] == "not": return str else: return "not " + str def missing_char(str, n): return str[:n] + str[n + 1:] def front_back(str): if len(str) <= 1: return str else: return str[len(str) - 1] + str[1:len(str) - 1] + str[0] def front3(str): front = 3 if len(str) < front: front = len(str) new_str = str[:front] return new_str + new_str + new_str # Warmup-2 def string_times(str, n): new_str = "" for i in range(0,n): new_str = new_str + str return new_str def front_times(str, n): front = 3 if len(str) < 3: front = len(str) new_str = "" for i in range(0,n): new_str = new_str + str[:front] return new_str def string_bits(str): new_str = "" for i in range(0, len(str), 2): new_str = new_str + str[i] return new_str def string_splosion(str): new_str = "" for i in range(len(str)): new_str = new_str + str[:i+1] return new_str def last2(str): if len(str) < 2: return 0 last_2 = str[-2:] count = 0 for i in range(len(str) - 2): substring = str[i:i+2] if substring == last_2: count += 1 return count def array_count9(nums): count = 0 for item in nums: if item == 9: count += 1 return count def array_front9(nums): elements = len(nums) if elements > 4: elements = 4 result = False for i in range(elements): if nums[i] == 9: result = True return result def array123(nums): result = False for i in range(len(nums) - 2): if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3: result = True return result def string_match(a, b): count = 0 for i in range(len(a) - 1): sub1 = a[i:i + 2] sub2 = b[i:i + 2] if sub1 == sub2: count += 1 return count
2570ddcfb945d60737907e503206cbb4edd62ae5
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Z_shen/lesson08/circle.py
1,356
3.921875
4
import math class Circle: def __init__(self, the_radius): self.radius = the_radius @property def diameter(self): return self.radius * 2 @diameter.setter def diameter(self, the_diameter): self.radius = the_diameter / 2 @property def area(self): return (self.radius ** 2) * math.pi @classmethod def from_diameter(cls, diameter): return cls(diameter / 2) def __str__(self): return self.__class__.__name__ + ' with radius: {}'.format(self.radius) def __repr__(self): return self.__class__.__name__ + '({})'.format(self.radius) def __add__(self, other): return Circle(self.radius + other.radius) def __mul__(self, other): return Circle(self.radius * other) def __rmul__(self, other): return Circle(self.radius * other) def __lt__(self, other): return self.radius < other.radius def __eq__(self, other): return self.radius == other.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)
0d5fd308f62f9a3975962cae198760abca9fb8aa
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/scotchwsplenda/Lesson_3/Exercises/slicing_lab.py
1,303
3.828125
4
a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) def first_last(x): '''with the first and last items exchanged.''' return x[-1:]+x[1:-1]+x[:1] assert first_last(a_string) == "ghis is a strint" assert first_last(a_tuple) == (32, 54, 13, 12, 5, 2) def ery_oth(x): '''with every other item removed.''' return x[::2] assert ery_oth(a_string) == "ti sasrn" assert ery_oth(a_tuple) == (2, 13, 5) def four_x_four(x): '''with the first 4 and the last 4 items removed, and then every other item in the remaining sequence.''' return x[4:-4:2] assert four_x_four(a_string) == " sas" assert four_x_four(a_tuple) == () def put_ur_tingdown(x): '''with the elements reversed (just with slicing).''' return x[::-1] assert put_ur_tingdown(a_string) == "gnirts a si siht" assert put_ur_tingdown(a_tuple) == (32, 5, 12, 13, 54, 2) trd_string = "123456789" trd_tuple = (2, 54, 13, 12, 5, 32) def thirds(x): '''with the last third, then first third, then the middle third in the new order.''' lgt = len(x) if lgt % 3 != 0: raise Exception("Give me something divisible by 3") trd = int(lgt/3) return x[-trd:]+x[:trd]+x[trd:-trd] assert thirds(trd_string) == "789123456" assert thirds(trd_tuple) == (5, 32, 2, 54, 13, 12)
983110b661be7abfd83e945bec77770a0fcae9e6
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jack_anderson/lesson03/mailroom.py
5,194
4.125
4
#!/usr/bin/env python3 """ Jack Anderson 02/14/2020 UW PY210 Mailroom assignment part 1 """ # The list of donors and their amounts donated donors_list = [ ['Bubbles Trailer',[1500, 2523, 3012]], ['Julien Park',[2520.92, 8623.12]], ['Ricky Boys',[7042.76, 3845.56, 5123.25]], ['Jack Anderson',[1044, 2232, 4123.56]], ['Lacey Coffin Greene',[7500.32, 6625, 1305, 3400.78]] ] def prompt_name(): name = input("Enter the full name of the donor (enter 'q' to cancel or 'list' to view a list of donors)\n") if name.lower() == "list": print(donor_names()) send_thanks() elif len(name) == 0: send_thanks() elif name.lower() == 'q': start() return name def prompt_donation(name): donation = input("Please enter a donation amount for {} " "(enter 'q' to cancel) : ".format(name)) if len(donation) == 0: send_thanks() elif donation.lower() == 'q': start() return float(donation) def donor_names(): # Return a list of donor names names = [] for donors in donors_list: names.append(donors[0]) return names def add_items(name, donation): """ Action to check if name exists in list and add name if not exists :param x: Name of donor :return: """ for donor in donors_list: if donor[0] == name: donor[1].append(donation) return else: new_donor = [name, [donation]] donors_list.append(new_donor) def get_donor_index(x): """ Action to search list by donor name and return index value of donor :param x: Name of donor :return: Index number of donor """ count = len(donor_names()) current = donor_names() index = 0 while index < count: if x == current[index]: return (index) index = index + 1 def donor_details(x): """ Action to summarize the details of a donor in the list :param x: The donors index number in the donor list :return: Name of donor, total amount donated, number of donations donor made, avg donation of donor """ donor = x name = donor[0] donations = donor[1] num_donations = len(donor[1]) total_donated = sum(donations) avg_donation = total_donated / num_donations return(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 print_email_template(name, amount): """ Action to print out donor email :param name: Name of the donor :param amount: The amount provided by the donor """ print() print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print(f"Hello {name},\n" f"Thank you for your gift of ${amount}! \n" f"We appreiate your gift to help with costs for our upcoming play! \n" f"Thank you for giving!\n" f"Best Regards, \n" f"The Blanchford Community Center!") print() def print_report_header(): 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 print_report_template(): """ Action to create a report :return: Print report header followed by summary of all donors """ print_report_header() for i in donors_list: name, totals, num_donations, avg_donation = donor_details(i) report_template(name, totals, num_donations, (avg_donation)) print() def send_thanks(): """ Action to prompt user for name then calls the name_check function and the prompt_donation_amount function """ name = prompt_name() donation = prompt_donation(name) add_items(name, donation) print_email_template(name, donation) 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: action = input("Select a number to perform one of the following actions...\n" "1. Send a Thank You Email \n" "2. Create a Report \n" "3. Quit \n") if action.isnumeric(): action = int(action) if action > 3 or action < 1: print("Please select a number 1, 2 or 3") elif action == 1: send_thanks() elif action == 2: print_report_template() elif action == 3: print("Quitting program ....") exit() else: print("Please enter a numerical value") if __name__ == '__main__': start()
02cd3405e8db0f877873ca0628b06481c6a362f0
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Shweta/lesson02/gridFunctionWithTwoArgs.py
523
4
4
#Print Grid Value using python function with two arguments def plusminus(n,m): for i in range(n): print('+',end=' ') print(('-' + ' ' ) * int(m),end=' ') print('+') def pipe(n,m): for i in range(m): for i in range(n+1): print('|',end=' ') print(' ' * int(m),end=' ') print() def print_grid(n,m): plusminus(n,m) for i in range(n): pipe(n,m) plusminus(n,m) print_grid(5,3)
0a7d8d494efb9b0e057c330a842c3967cd437013
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shodges/lesson03/list_lab.py
1,857
3.953125
4
#!/usr/bin/env python3 # series 1 fruits = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruits) fruitprompt = '' while not fruitprompt: fruitprompt = input('Name a fruit, any fruit! ') fruits.append(fruitprompt) print(fruits) fruitprompt = input('Ok, now pick a number! ') if int(fruitprompt) < 1: # this will technically /work/ but it's not in the spirit of the problem :) print("I don't have a fruit number {}".format(fruitprompt)) else: try: print("Fruit number {} is {}".format(fruitprompt, fruits[int(fruitprompt)-1])) except: # catch all manner of bad input, including not numbers and bad indicies print("I don't have a fruit number {} :()".format(fruitprompt)) newfruit = 'Kiwi' fruits = [newfruit] + fruits print(fruits) fruits.insert(0, 'Dragonfruit') print(fruits) print("All the fruits that start with the letter of the day .. 'P'!") for fruit in fruits: if fruit.startswith('P'): print(fruit) # series 2 fruits2 = fruits[:] print(fruits2) fruits2.remove(fruits2[-1]) print(fruits2) fruits2 = fruits2*2 while True: fruitprompt = input('What fruit are we deleting? ') if fruitprompt in fruits2: break while fruitprompt in fruits2: fruits2.remove(fruitprompt) #series 3 fruits3 = fruits[:] for fruit in fruits: #purposely iterating through the original here -- if we remove an element inside the for loop, we'll skip over the next element while True: response = input('Do you like {}? [yes, no] '.format(fruit.lower())) if response == 'no': fruits3.remove(fruit) break elif response == 'yes': break print(fruits3) #series 4 fruits4 = [] for fruit in fruits: fruits4 += [fruit[::-1]] fruits.remove(fruits[-1]) print('Copied list:') print(fruits4) print('Original list:') print(fruits)
027f7918bb095a8577f812a04f1872ae0ca83b74
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/stellie/lesson04/mailroom2.py
4,569
4.3125
4
#!/usr/bin/env python3 # Stella Kim # Assignment 2: Mailroom Part 2 """ This program lists donors and their donation amounts. A user is able to choose from a menu of 3 donation-related actions: send a thank you, create a report or quit the program. """ import sys # Lists donors and their contributions donor_db = {'John Smith': [10000, 5000, 1000], 'Mary Johnson': [50000], 'David Carlton': [2500, 500], 'James Wright': [500, 500, 500], 'Caroline Baker': [1000] } # Displays menu options to user prompt = '\n'.join(('\nWelcome to the mail room.', 'Please choose from the below options:', '1 - Send a Thank You', '2 - Create a report', '3 - Send letters to all donors', '4 - Quit', '>>> ')) def invalid_option(): print('\nThat is not a valid option. Please choose one of the three options above.') def send_thank_you(): # Prompts user to choose a thank you note option user_response = input('\nPlease enter your full name or type "list" to view the list of donors.\nIf you would like to see the main menu type "menu": ') if user_response == 'list': view_donors() send_thank_you() elif user_response == 'menu': main() else: donor = search_db(user_response) # calls function to search for already existing donor if donor: print('\nThis donor already exists in our database.') donation = donation_amount() # calls function to obtain donation amount made donor_db[donor].append(donation) # adds donation amount to existing donor in database thank_you_email(donor, donation) else: print('\nThis is a NEW donor and will be added to the database.') donation = donation_amount() # calls function to obtain donation amount made donor_db[user_response] = [donation] # adds new donor and donation to database thank_you_email(user_response, donation) # Displays list of donors def view_donors(): print('\nThe following is the list of donors:') for donor in donor_db.keys(): print(donor) # Searches database to see if user already exists def search_db(donor_name): for record in donor_db.keys(): if record == donor_name: return record return None # Prompts user to enter a donation amount def donation_amount(): user_donation = input('Please enter the amount you would like to donate: $') return float(user_donation) # Sends donor a thank you email def thank_you_email(donor_name, amount): print(f'\nThank you {donor_name} for your generous donation amount of ${amount:.2f}. We hope to see you again soon.') # Creates a report for user to see list of all donors and donations made def create_report(): print('\n{:<20} | {:<12} | {:<10} | {:<15}'.format('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')) print('=' * 65) donor_list = list(donor_db.items()) # create list out of database to iterate through sorted_db = sorted(donor_list, key=sum_total, reverse=True) # sorts database by sum amounts in descending order for item in sorted_db: total = sum(item[1]) # sum of all donations count = len(item[1]) # total number of donations average = total/count # average of all donations print(f'{item[0]:<20} | {total:<12.2f} | {count:<10} | {average:<15.2f}') # Sums donation amounts for each donor record and returns amounts for sorted database def sum_total(donor_record): return(sum(donor_record[1])) # Sends letters to all donors for their donations def send_letters(): for record in list(donor_db.items()): file_name = f'{record[0]}.txt' # creates file name using name of donor new_file = open(file_name, 'w') # creates a new file donor_letter = f'Dear {record[0]},\n\nThank you for your {len(record[1])} donations that total ${sum(record[1]):.2f}.\nIt will be put to very good use.\n\n\tSincerely,\n\t-The Team' new_file.write(donor_letter) # writes the letter to the text file new_file.close() # Exits the program def exit_program(): print('\nThank you for visiting!') sys.exit() # Main menu options for user to choose for mail program def main(): switch_dict = { 1: send_thank_you, 2: create_report, 3: send_letters, 4: exit_program } while True: response = int(input(prompt)) switch_dict.get(response, invalid_option)() if __name__ == "__main__": main()
7a2ce3573a8b7fbbdc4225e7ee8ff97bf77433cc
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/headieh_godwin/lesson02/grid_printer.py
953
3.75
4
#PART 1 print('Part 1') def grid(): column = '+' + ' -' * 4 + '+' + ' -' * 4 + '+' rows = '|' + ' ' * 8 + '|' + ' ' * 8 + '|' print (column) print (rows) print (rows) print (rows) print (rows) print (column) print (rows) print (rows) print (rows) print (rows) print (column) grid() #PART 2 print('Part 2') def print_grid(n): time = int(round((n-1)/2)) rows = '+' + ' -' * time + ' +' + ' -' * time + ' +' column = '|' + ' ' * time + ' |' + ' ' * time + ' |' for i in range (2): print (rows) for j in range (time): print(column) print(rows); print_grid(15) #PART 3 print('Part 3') def print_grid2(n,m): rows = '+' + (' -'* m+ ' +')*n column = ('| ' + ' ' * m)*(n+1) for i in range (n): print (rows) for j in range (m): print(column) print(rows); print_grid2(3,4) print_grid2(5,3)
8bf48446e7fc571eba9629738e3be6fd559f0168
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/humberto_gonzalez/session09/cli_main.py
2,696
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 21 12:47:23 2019 @author: humberto """ import sys from donor_models import donorCollection from donor_models import Donor #Intializing a donor database donorA = Donor("Tyrod Taylor") donorA.add_donation(1000) donorA.add_donation(50) donorA.add_donation(15) donorB = Donor("Philip Rivers") donorB.add_donation(100) donorB.add_donation(500) donorB.add_donation(155) donorC = Donor("Cam Newton") donorC.add_donation(200) donorC.add_donation(540) mailroom_db = donorCollection() mailroom_db.add_donor(donorA) mailroom_db.add_donor(donorB) mailroom_db.add_donor(donorC) 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 obtain_donation_info(): """Prompts user for a donor and donation amount""" donor_name = input('What is the full name of the donor you would like to thank? ') if donor_name.lower() == "quit": main() donation = input('What was the donation amount? ') try: float(donation) except ValueError: print('Donation amount needs to be a number, please enter a number') donation = input('What was the donation amount? ') if donation.lower()=="quit": main() return donor_name, donation def send_thank_you(): """Prompts user for a donor and donation amount, and then prints out a thank you email""" donor_name, donation = obtain_donation_info() new_donor = Donor(donor_name) new_donor.add_donation(donation) mailroom_db.add_donor(new_donor) txt = new_donor.generate_thank_you_note() print() print() print(txt) def exit_program(): """ exits the main 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":mailroom_db.display_report, "3":mailroom_db.send_letters, "4":exit_program} try: menu_options.get(response)() except Exception as e: print() print("Please select one of the available options") print("You will be returned to the main menu") continue if __name__ == "__main__": # don't forget this block to guard against your code running automatically if this module is imported main()
b0cdb8c87c76f5f383b473fb57aadb72d3399e06
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/csimmons/lesson02/series.py
2,274
4.46875
4
#!/usr/bin/env python3 # Craig Simmons # Python 210 # series.py - Lesson02 - Fibonacci Exercises # Created 11/13/2020 - csimmons # Modified 11/14/2020 - csimmmons def sum_series(n,first=0,second=1): """ Compute the nth value of a summation series. :param first=0: value of zeroth element in the series :param second=1: value of first element in the series This function should generalize the fibonacci() and the lucas(), so that this function works for any first two numbers for a sum series. Once generalized that way, sum_series(n, 0, 1) should be equivalent to fibonacci(n). And sum_series(n, 2, 1) should be equivalent to lucas(n). sum_series(n, 3, 2) should generate another series with no specific name The defaults are set to 0, 1, so if you don't pass in any values, you'll get the fibonacci sercies """ if n == 0: return(first) elif n == 1: return(second) else: return sum_series(n-2,first,second) + sum_series(n-1,first,second) pass def fibonacci(n): """ Compute the nth Fibonacci number """ return sum_series(n) pass def lucas(n): """ Compute the nth Lucas number """ return sum_series(n,2,1) pass 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(2) == 3 assert lucas(3) == 4 assert lucas(4) == 7 assert lucas(5) == 11 assert lucas(6) == 18 assert lucas(7) == 29 # 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) assert sum_series(7, 2, 1) == lucas(7) # 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("All tests passed")
31db82ae7a9a15b025028945516694867086de4b
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shodges/lesson08/test_circle.py
6,091
3.6875
4
#!/usr/bin/env python3 import pytest, math from circle import * def test_create_circle(): """ Test creation of a circle and output of its radius. Expected output is: c1 -- raises TypeError c2 == 8 c3 == 3.14 """ # Validate getting a TypeError if we don't pass a numeric radius with pytest.raises(TypeError): c1 = Circle('boo') # We should be able to set the radius to an integer... c2 = Circle(8) assert c2.radius == 8 #... or a float c3 = Circle(3.14) assert c3.radius == 3.14 def test_diameter(): """ Test that the diameter property is set. Expected output: c.radius == 4 c.diameter == 8 """ c = Circle(4) assert c.radius == 4 assert c.diameter == 8 def test_update_diameter(): """ Test that the diameter can be manipulated, and the radius is updated in tandem. Expected output: c.radius (initial) == 3.5 c.diameter (initial) == 7 c.radius (updated) == 2.25 c.diameter(updated) = 4.5 """ c = Circle(3.5) assert c.radius == 3.5 assert c.diameter == 7 c.diameter = 4.5 assert c.radius == 2.25 assert c.diameter == 4.5 def test_update_radius(): """ Test that the radius can be manipulated, and the diameter is updated in tandem. Expected output: c.radius (initial) == 4.25 c.diameter (initial) == 8.5 c.radius (updated) == 1.8 c.diameter(updated) = 3.6 """ c = Circle(4.25) assert c.radius == 4.25 assert c.diameter == 8.5 c.radius = 1.8 assert c.radius == 1.8 assert c.diameter == 3.6 def test_area(): """ Test that the area is calculated and cannot be set. Expected output: c.area == ((5)^2) * pi """ c = Circle(5) assert c.area == math.pow(5, 2) * math.pi with pytest.raises(AttributeError): c.area = 42 def test_define_with_diameter(): """ Test that the class can be instantiated using the from_diameter() classmethod. Expected output: c1.diameter == 15.5 c1.radius == 7.75 c2 -- raises TypeError """ c1 = Circle.from_diameter(15.5) assert c1.diameter == 15.5 assert c1.radius == 7.75 with pytest.raises(TypeError): c2 = Circle.from_diameter('test') def test_str_repr(): """ Test the __str__ and __repr__ methods. Expected output: str(c) == String with radius 10.00000 repr(c) == Circle(10) """ c = Circle(10) assert str(c) == 'Circle with radius 10.00000' assert repr(c) == 'Circle(10.0)' def test_arithmetic(): """ Test the ability to add, subtract, multiply and divide circle objects. Expected output: (c1 + c2).radius == 15.5 (c1 + 5).radius == 15 (c1 - 2.3).radius == 7.7 (c1 * c2).radius == 55 (c1 * 3).radius == 30 (c1 / 4).radius == 2.5 (8 + c2).radius == 13.5 (9 - c2).radius == 3.5 (4 * c1).radius == 40 (80 / c1).radius == 8 """ c1 = Circle(10) c2 = Circle(5.5) assert (c1 + c2).radius == 15.5 assert (c1 + 5).radius == 15 assert (c1 - 2.3).radius == 7.7 assert (c1 * c2).radius == 55 assert (c1 * 3).radius == 30 assert (c1 / 4).radius == 2.5 assert (8 + c2).radius == 13.5 assert (9 - c2).radius == 3.5 assert (4 * c1).radius == 40 assert (80 / c1).radius == 8 def test_comparison(): """ Test the ability to compare circle objects. Expected output: c1 < c2 c2 > c4 c1 >= c3 c1 >= c4 c4 <= c3 c3 >= c1 c1 == c3 c1 != c4 """ c1 = Circle(10) c2 = Circle(12.5) c3 = Circle(10) c4 = Circle(3) assert c1 < c2 assert c2 > c4 assert c1 >= c3 assert c1 >= c4 assert c4 <= c3 assert c3 >= c1 assert c1 == c3 assert c1 != c4 def test_ordering(): """ Test ordering Circle objects. Expected output: [Circle(1.0), Circle(1.5), Circle(3.0), Circle(4.5), Circle(5.0), Circle(5.25), Circle(8.0)] """ circles = [Circle(8), Circle(4.5), Circle(3), Circle(5), Circle(1), Circle(5.25), Circle(1.5)] circles.sort() print(circles) assert circles == [Circle(1.0), Circle(1.5), Circle(3.0), Circle(4.5), Circle(5.0), Circle(5.25), Circle(8.0)] def test_reflective_augmented(): """ Test reflected and augmented arithmetic functions. Expected output: 2 + c1 == Circle(10) 4 - c2 == Circle(1) 9 * c2 == Circle(27) 12 / c2 == Circle(4) c2 += 4, c2 == Circle(7) c1 += c2, c1 == Circle(15) c1 -= c2, c1 == Circle(8) c1 -= 2, c1 == Circle(6) c1 *= c2, c1 == Circle(42) c2 *= 9, c2 == Circle(63) c1 /= c3, c1 == Circle(21) c2 /= 3, c2 == Circle(21) """ c1 = Circle(8) c2 = Circle(3) c3 = Circle(2) assert 2 + c1 == Circle(10) assert 4 - c2 == Circle(1) assert 9 * c2 == Circle(27) assert 12 / c2 == Circle(4) c2 += 4 assert c2 == Circle(7) c1 += c2 assert c1 == Circle(15) c1 -= c2 assert c1 == Circle(8) c1 -= 2 assert c1 == Circle(6) c1 *= c2 assert c1 == Circle(42) c2 *= 9 assert c2 == Circle(63) c1 /= c3 assert c1 == Circle(21) c2 /= 3 assert c2 == Circle(21) def test_sphere(): """ Test functionality of the Sphere subclass Expected output: s1.diameter == 24 s1.area == 4*pi*(12^2) s1.volume == (4/3)*pi*(12^3) str(s1) == Sphere with radius 12.00000 repr(s1) == Sphere(12) s2.radius == 5 """ s1 = Sphere(12) assert s1.diameter == 24 assert s1.area == 4 * math.pi * math.pow(s1.radius,2) # This was in a different order than the function which resulted in a different value # in the 12th decimal place, failing this test. Guessing Cpython is casting to a float # at different points resulting in different precision? assert s1.volume == (4/3) * math.pow(s1.radius, 3) * math.pi assert str(s1) == 'Sphere with radius 12.00000' assert repr(s1) == 'Sphere(12.0)' s2 = Sphere.from_diameter(10) assert s2.radius == 5
296b00ca421cdc03c20700e901c77bf760babb5a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jason_jenkins/lesson01/Logic2.py
1,325
3.59375
4
# Lesson 1: Logic2 def make_bricks(small, big, goal): if(big != 0) and big > goal // 5: big = goal // 5 return big * 5 + small >= goal def lone_sum(a, b, c): sum = 0 if (a != b and a != c): sum += a if (b != a and b != c): sum += b if (c != a and c != b): sum += c return sum def lucky_sum(a, b, c): if a == 13: return 0 if b == 13: return a if c == 13: return a + b return a + b + c def no_teen_sum(a, b, c): return fix_teen(a) + fix_teen(b) + fix_teen(c) def fix_teen(n): if(13 <= n <= 19): if not (15 <= n <= 16): return 0 return n def round_sum(a, b, c): return round10(a) + round10(b) + round10(c) def round10(num): if(num % 10 >= 5): return num + (10 - (num % 10)) else: return num - (num % 10) def close_far(a, b, c): if abs(a - b) <= 1: if abs(a - c) > 1 and abs(b - c) > 1: return True if abs(a - c) <= 1: if abs(a - b) > 1 and abs(b - c) > 1: return True return False def make_chocolate(small, big, goal): if (goal // 5 < big): big = goal // 5 maxCount = big * 5 + small if (maxCount >= goal): return goal - big * 5 else: return -1
4174277a463cf7388a64db50feda0265596121ba
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/andrew_garcia/lesson_02/Grid_Printer_3.py
1,306
4.21875
4
''' Andrew Garcia Grid Printer 3 6/2/19 ''' def print_grid2(row_column, size): def horizontal(): # creates horizontal sections print('\n', end='') print('+', end='') for number in range(size): # creates first horizontal side of grid print(' - ', end='') print('+', end='') for number in range(row_column - 1): # selects number of extra columns for number in range(size): # creates size of grid print(' - ' , end='') print('+', end='') def vertical(): # creates vertical sections for number in range(size): # creates firstv vertical side of grid print('\n', end='') print('|', end='') print((' ' * size), end='') print('|', end='') for number in range(row_column - 1): # selects number of extra rows print(' ' * size, end='') # creates size of grid print('|', end='') def final_grid(): #combines vertical and horizontal sections for number in range(row_column): horizontal() vertical() horizontal() final_grid() row_column, size = int(input("Enter Number of Rows and Columns: ")), int(input("Enter Size of Grid: ")) print_grid2(row_column, size)
69f216e230869960e7faea947d04f23d5249efe0
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kimc05/Lesson09/cli_main.py
4,360
4.0625
4
#!/usr/bin/env python3 """ Christine Kim Lesson 9 Client class """ import sys from donor_models import Giver from donor_models import GiverCollection #Donor dictionary created givetree = GiverCollection({"Cullen Rutherford": Giver("Cullen Rutherford", [1500, 4200, 50000]), "Alistair Theirin": Giver("Alistair Theirin", [200, 80000, 1500000]), "Zevran Arainai": Giver("Zevran Arainai", [50]), "Solona Amell": Giver("Solona Amell", [2, 500000, 2000000]), "Soufehla Lavellan": Giver("Soufehla Lavellan", [70, 600])}) #Prompt for user to be displayed prompt = ("\nWelcome to the Blight Orphans Charity. Plase select from the following options.\n" "1: Send a Thank You to a Single Donor\n" "2: Create a Report\n" "3: Send a Letter to All\n" "4: Quit\n") # --------------------------------------------------------------------------- #method for sending thank you to donor def thank_you(): #receive donor name from user input giver_name = input("\nPlease enter the full name in 'first name' 'last name' format,\n" "or type 'list' to display names on the record: ") while giver_name.lower() == "list": #display list of donor names print(givetree.names()) giver_name = input("\nPlease enter the full name of the donor: ") #in case of not full name while True: try: #split first/last name first_last = giver_name.split() first_name = first_last[0].capitalize() last_name = first_last[1].capitalize() #receive new info except IndexError: print("You've not entered a full name. Please enter the full name of the donor in 'first name' 'last name' format.") giver_name = input("\nPlease enter the full name of the donor in 'first last' format,\n" "or type 'list' to display names on the record: ") while giver_name.lower() == "list": #display list of donor names print(givetree.names()) giver_name = input("\nPlease enter the full name of the donor: ") else: break #update name with capitalized format giver_name = "{} {}".format(first_name, last_name) #catch bad user input while True: try: #prompt user for donation amount received = int(float(input("\nPlease enter the amount of donation: "))) except ValueError: print("\nPlease enter a numeric donation amount") else: break giver = Giver(giver_name, received) #update donor information givetree.add_giver(giver, received) #print thank you email print(giver.gratitude(received)) # --------------------------------------------------------------------------- #create donation histroy report for user def report(): #print report header header() #print report content givetree.report_givers() #write report header def header(): print("\nBlight Orphans Charity Donation Report") header = "\n{:<30}|{:^15}|{:^10}|{:^15}".format("Donor Name", "Total Given", "Num Gifts", "Average Gift") print(header) print("-" * len(header)) # --------------------------------------------------------------------------- #write letter to all donors def letters(): for person in givetree.dict_givers().values(): with open(f"{person.name}.txt", "w") as outfile: outfile.write(person.gratitude(person.total_v())) # --------------------------------------------------------------------------- #quit the script def end(): print("\nThank you for your patronage. Farewell!\n") sys.exit() # --------------------------------------------------------------------------- #method for menu selection def menu(prompt, dispatch_dict): while True: #receive user input response = input(prompt) #Catch bad user input try: #direct user to proper function dispatch_dict[response]() except KeyError: print("\nPlease choose from 1, 2, 3, or 4") #main menu dictionary menu_dict = {"1": thank_you, "2": report, "3": letters, "4": end} if __name__ == '__main__': #initiate menu selection menu(prompt, menu_dict)
baaeed4242ead2433cba47252658bf0ca575c5b7
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/zach_meves/lesson08/circle.py
3,347
4.59375
5
""" circle.py Zachary Meves Python 210 Lesson 08 Circle Assignment """ import math class Circle: """A class defining a circle.""" def __init__(self, radius: float): """Construct a circle with a given radius. Parameters ---------- radius : float Radius to initialize circle with """ self._radius = 0 self.radius = radius @property def radius(self): """The circle's radius.""" return self._radius @radius.setter def radius(self, new_radius: float): if new_radius >= 0: self._radius = float(new_radius) else: raise ValueError("Radius must be >= 0") @property def diameter(self): """The circle's diameter.""" return 2 * self._radius @diameter.setter def diameter(self, new_diameter: float): self.radius = new_diameter / 2 @property def area(self) -> float: """Area of the circle.""" return math.pi * self.radius ** 2 @classmethod def from_diameter(cls, diameter: float): """Construct a Circle with a given diameter. Parameters ---------- diameter : float Diameter of Circle to make. Returns ------- Circle Circle with given diameter """ return cls(diameter / 2) def __repr__(self): return f"Circle({self.radius:g})" def __str__(self): return f"Circle with radius: {self.radius:.6f}" def __add__(self, other): try: return Circle(self. radius + other.radius) except AttributeError: raise TypeError("A Circle can only be added with another Circle") def __radd__(self, other): return self.__add__(other) def __sub__(self, other): try: return Circle(self.radius - other.radius) except AttributeError: raise TypeError("A Circle can only be subtracted from another Circle.") def __rsub__(self, other): return self.__sub__(other) def __mul__(self, other): try: return Circle(self.radius * other) except AttributeError: raise TypeError("A Circle can only be multiplied by a number.") def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): return self.__mul__(1 / other) def __lt__(self, other): return self.radius < other.radius def __le__(self, other): return self.radius <= other.radius def __eq__(self, other): return self.radius == other.radius def __ne__(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 __pow__(self, power, modulo=None): return Circle(self.radius ** power) class Sphere(Circle): """A class defining a sphere.""" @property def volume(self): """Volume of the sphere.""" return 4/3 * math.pi * self.radius ** 3 @property def area(self): return 4 * super().area def __repr__(self): return f"Sphere({self.radius:g})" def __str__(self): return f"Sphere with radius: {self.radius:.6f}"
f6463a3d08dd4150f242193982444722f533bcd7
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kimc05/Lesson03/List_lab.py
2,427
4.34375
4
#!/usr/bin/env python3 #Christine Kim #Series 1 print("Series 1") print() #Create and display a list of fruits fruits = ["Apples", "Pears", "Oranges", "Peaches"] print(fruits) #Request input from user for list addition fruits.append(input("Input a fruit to add to the list: ")) print(fruits) #Request input from user for a number and display the number and corresponding fruit fruit_num = int(input("There are {} fruits in the list. Input a number for a fruit to display: ".format(len(fruits)))) print(str(fruit_num) + ": " + fruits[(fruit_num - 1)]) #Add to the beginning of the list with '+' fruits = [input("Input a fruit to add to the beginning of the list: ")] + fruits print(fruits) #Add to the beginning of the list with 'insert()' fruits.insert(0, input("Input a fruit to add to the beginning of the list: ")) print(fruits) #Use a for loop to display all fruits beginning with "P" print("Displaying all fruits which starts with a 'P': ") for item in fruits: if item[0] == "P" or item[0] == "p": print(item) #Series 2 print() print("Series 2") print() #Display list fruits2 = fruits[:] print(fruits2) #Remove the last item on the list and display fruits2.pop() print(fruits2) #Request input for fruit to delete del_fruit = input("Input a fruit to remove from the list: ") if del_fruit in fruits2: fruits2.remove(del_fruit) else: print("Entry not found.") #Display updated list print(fruits2) #Series 3 print() print("Series 3") print() #Use list from Series 1 fruits3 = fruits[:] print(fruits3) #Perform action for every item in the list sadfruits = [] for item in fruits3: while True: #Request user prefrence input answer = input("Do you like " + item.lower() + "? ") #Next if answer == "yes": break #mark disliked fruits elif answer == "no": sadfruits.append(item) break #prompt user for proper entry else: print("Please respond in either 'yes' or 'no'") #Remove disliked fruits for fruit in sadfruits: fruits3.remove(fruit) #Display updated list print(fruits3) #Series 4 print() print("Series 4") print() #New list with contents of the original reversed fruits4 = [] for item in fruits: item = item[::-1] fruits4.append(item) #Delete last item of the original list fruits4.pop() #Display original list and the copy print(fruits) print(fruits4)
80bc9ed69ccd8bb57fe2422825335ca4ed591762
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kevin_t/lesson2/ex1_grid_printer.py
974
4
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 1 14:36:21 2019 @author: Kevin """ def print_grid2(num_box, size_box): #This section concatenates the symbols to create the first line of the box #It considers the number of boxes and size of each box (how many dashes) line1 = '+' line1 = line1 + num_box*(size_box* ' -' + ' +') #This section concatenates the symbols to create the second line of the box #It considers the number of spaces between vertical lines, and the number of vertical lines line2 = '|' line2 = line2 + num_box*(size_box* ' ' + ' |') #This prints the first line print (line1) #This for loop adds on the remaining 3 sides of each box, looped for the number of boxes for i in range(num_box): #This loop prints the vertical lines for each box, as a function of box size for j in range(size_box): print (line2) #This prints the bottom of the box. print (line1)
b41b3820140b20afb147a6fba93c3aed3849c851
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/randi_peterson/session02/GridPrinter_Exercises/GridPrinter_Part3.py
705
3.984375
4
#This Prints the grid for Part 3 of Lesson 2 #This code expands on part 2 to allow choosing of grid format and size def GridPrinterPart3(dims,units): #Print grid of the size specified by the user dashes = "- " * units #Set spacing for upright bars spaces = " " *(len(dashes) + 1) #Creates +-+ rows, deletes extra space at the end of row horizontal_row = "+ " + dims*(dashes + "+ ") horizontal_row = horizontal_row[0:-1] bar_row = "|" + (spaces + "|")*dims #Prints the first row of + and -, then loops to create full grid print(horizontal_row) for row in range(0,dims): for x in range(0,units): print(bar_row) print(horizontal_row)
24b09f598775e57758b7110bfb5bf8573bb109af
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Jaidjen/lesson03/SlicingLab.py
616
3.671875
4
def first_and_last(seq): return seq[-1:] + seq[1:-1] + seq[:1] myseq = first_and_last("Reverse the order of words") print(myseq) def rem_item(seq): return seq[::2] myseq1 = rem_item("Reverse the order of words") print(myseq1) def rem_four(seq): return seq[4:-4:2] myseq2 = rem_four("Reverse the order of words") print(myseq2) def swap_words(seq): return(' '.join(seq.split()[::-1])) myseq3 =swap_words("Reverse the order of words") print(myseq3) def mix_items(seq): # ofs =(len(seq)//2 return seq.strip()[0:-3:3] myseq4 = mix_items("Reverse the order of words") print(myseq4)
30d8e4659c6e2a377a2f0df3375646aa527ae7de
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/paul_cooper/lesson_3/list_lab.py
1,014
3.921875
4
# Series 1 fruits = ['Apples','Pears','Oranges','Peaches'] print(fruits) user_fruit = [input('Please name another fruit. ')] fruits = fruits + user_fruit print(fruits) num = int(input('Please give a number. ')) print(num, fruits[num-1]) fruits = ['Bananas']+fruits print(fruits) fruits.insert(0,'Strawberrys') print(fruits) for i in fruits: if 'P' in i: print(i) # Series 2 fruits2 = fruits.copy() print(fruits2) del fruits2[-1:] print(fruits2) user_del_fruit = input("Name a fruit to be deleted. ") fruits2.remove(user_del_fruit) # Series 3 fruits3 = fruits.copy() for i in fruits3[:]: print('Do you like ', i.lower()+'?') question = input('') while question != 'yes' and question != 'no': print('Please enter yes or no.') question = input("") if question == 'yes': continue elif question == 'no': fruits3.remove(i) print(fruits3) # Series 4 fruits4 = fruits.copy() newlist = [] for i in fruits4: newlist = newlist + [i[::-1]] del fruits[-1:] print(newlist) print(fruits) print(fruits4)
47496e40702fa399ae03bc775318aa066a171394
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/steve_walker/lesson01/task2/logic-2_make_bricks.py
451
4.375
4
# Logic-2 > make_bricks # We want to make a row of bricks that is goal inches long. We have a number of # small bricks (1 inch each) and big bricks (5 inches each). Return True if it # is possible to make the goal by choosing from the given bricks. This is a # little harder than it looks and can be done without any loops. def make_bricks(small, big, goal): if small + 5*big < goal or small < goal % 5: return(False) else: return(True)
3fcd14e1c53a3d2eda0d65f64f6eab1c87aca701
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chrissp/lesson04/trigrams.py
3,810
4.25
4
#!/usr/bin/env python3 import sys import os import random import string prompt = "\n".join(("Welcome to the story maker!", "Please input a source file name.", ">>> ")) prompt_words = "\n".join(("How many words would you like your story to be?", ">>> ")) def load_text(filename): """ Open the file by the file name and return text. :param filename: name of file as a string with extension :return a string of file content """ with open(filename, 'r') as file: read_data = file.read() file.close return read_data def make_words(input_text): word_list = [] keep_words = False lines = input_text.split("\n") for line in lines: if len(line) > 0: # Skip header starting on the line after *** if line.split(" ")[0] == "***": keep_words = True elif keep_words: if line.split(" ")[0] == "***": break line_words = line.split(" ") for word in line_words: if len(word) > 0: word_list.append(word) return word_list def build_trigrams(words): """ Build up the trigrams dict from the list of words. returns a dict with: keys: word pairs values: list of followers """ trigrams = {} for i in range(len(words)-2): pair = words[i:i + 2] key = (pair[0], pair[1]) follower = words[i + 2] trigrams.setdefault(key, []).append(follower) return trigrams def build_text(trigram_dict, word_limit): trigram_keys = list(trigram_dict.keys()) # Initial seeding of words with random selection this_key = trigram_keys[random.randint(0, len(trigram_keys) - 1)] third_word = trigram_dict.get(this_key)[random.randint(0, len(trigram_dict.get(this_key)) - 1)] word_list = [this_key[0].capitalize(), this_key[1], third_word] # Loop until word limit is reached while len(word_list) < word_limit: quote_open = False this_key = (word_list[-2], word_list[-1]) if this_key in trigram_dict: third_word = trigram_dict.get(this_key)[random.randint(0, len(trigram_dict.get(this_key)) - 1)] if "." or "?" or "!" in word_list[-1]: third_word.capitalize() if third_word[0] == "\"": quote_open = True if third_word[-1] == "\"" and not quote_open: third_word = third_word[:-1] else: quote_open = False word_list.append(third_word) else: third_word = trigram_dict.get(this_key)[random.randint(0, len(trigram_dict.get(this_key)) - 1)] word_list.append(third_word) if "." not in word_list[-1]: word_list[-1] = word_list[-1] + "." return word_list def final_text(word_list): for word in word_list: if word[-1] == "\"": word = word + "\n\n" print(" ".join(word_list)) def quit_program(): print("You're welcome!", "See you next time!") sys.exit() def main(): # get the filename from the command line while True: filename = input(prompt) if filename.lower() == "exit" or filename.lower() == "quit": print("Aaaannnddd, scene!") quit_program() if filename.lower() == "list": print(os.listdir()) main() word_count = float(input(prompt_words)) file_data = load_text(filename) words = make_words(file_data) trigrams = build_trigrams(words) new_text = build_text(trigrams, word_count) final_text(new_text) quit_program() if __name__ == "__main__": main()
7c9c1a235810e9b3b3ed02099b481e6032eb5f54
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Deniss_Semcovs/Lesson04/trigrams.py
728
4.125
4
# creating trigram words = "I wish I may I wish I might".split() import random def build_trigrams(words): trigrams = {} for i in range(len(words)-2): pair = tuple(words[i:i+2]) follower = [words[i+2]] if pair in trigrams: trigrams[pair] += follower else: trigrams[pair] = follower return (trigrams) if __name__=="__main__": trigrams = build_trigrams(words) print(trigrams) # generating random word combinations first_word = words[0]+" " sentence = "" print(first_word+" ".join(trigrams[random.choice(list(trigrams.keys()))])) for i in trigrams: sentence += " ".join(trigrams[random.choice(list(trigrams.keys()))])+" " print(first_word+sentence)
3b18a1e0c4d9e93df20b379f0e4d1a0b23af7739
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Kristy_Martini/lesson03/strformat_lab_kmarti.py
2,283
3.578125
4
def task_one(a_tuple): str0 = str(a_tuple[0]).rjust(3,'0') str1 = '{0:8.2f}'.format(a_tuple[1]) str2 = '{0:.2e}'.format(a_tuple[2]) str3 = '{0:.3e}'.format(a_tuple[3]) task_one_str = 'file_{} : {}, {}, {}'.format(str0, str1, str2, str3) print(task_one_str) return task_one_str def task_two(a_tuple): str0 = str(a_tuple[0]).rjust(3,'0') str1 = '{0:8.2f}'.format(a_tuple[1]) str2 = '{0:.2e}'.format(a_tuple[2]) str3 = '{0:.3e}'.format(a_tuple[3]) task_two_str = f'file_{str0} : {str1}, {str2}, {str3}' print(task_two_str) return task_two_str def task_three(a_tuple): num_values = len(a_tuple) task_three_str = ('the {} numbers are: ' +", ".join(["{}"] * num_values)).format(num_values, *a_tuple) print(task_three_str) return(task_three) def task_four(b_tuple): str0 = str(b_tuple[3]).rjust(2,'0') str3 = str(b_tuple[0]).rjust(2,'0') task_four_str = f'{str0} {b_tuple[4]} {b_tuple[2]} {str3} {b_tuple[1]}' print(task_four_str) return task_four_str def task_five(c_list): # task_five_str = f'The weight of an {c_list[0][:-1]} is {c_list[1]} and the weight of a {c_list[2][:-1]} is {c_list[3]}' task_five_str = f'The weight of an {c_list[0][:-1].upper()} is {c_list[1]*1.2} and the weight of a {c_list[2][:-1].upper()} is {c_list[3]*1.2}' print(task_five_str) def task_six(list_tuples): print(('Name'.ljust(9,' ')), ('Age'.ljust(4,' ')), ('Cost'.ljust(8,' '))) for entry in list_tuples: name = entry[0].ljust(10,' ') age = str(entry[1]).ljust(5, ' ') cost = '$' + str(entry[2]).ljust(8, ' ') print(f'{name}{age}{cost}') #Extra Task ten_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) task_tuple_string = ("".join(["{:<5.0f}"] * len(ten_tuple))).format(*ten_tuple) print(task_tuple_string) if __name__ == "__main__": a_tuple = (2, 123.4567, 10000, 12345.67) b_tuple = (4, 30, 2017, 2, 27) c_list = ['oranges', 1.3, 'lemons', 1.1] d_tuple = ('Kristy', 25, 100) e_tuple = ('Matt', 26, 1800) f_tuple = ('Katie', 25, 14000) list_tuples = [d_tuple, e_tuple, f_tuple] task_one(a_tuple) task_two(a_tuple) task_three(a_tuple) task_four(b_tuple) task_five(c_list) task_six(list_tuples)
7fae55365ce8fa7a5cf4f069c86e43c963762724
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/cbrown/Lesson 3/mailroom.py
3,085
4
4
#!/usr/bin/env python3 #Mailroom script part one. Using list data structures import sys donors = [("Bill Gates",[539000,235642]), ("Jeff Bezos",[108356,204295,897345]), ("Satya Nadella",[236000,305352]), ("Mark Zuckerberg",[153956.35]), ("Mark Cuban",[459035,369.50,570.89])] prompt = "\n".join(("Please Select from Items Below:", "1 - Send A Thank You", "2 - Create A Report", "3 - Quit", " ")) def send_thanks(): print('\n',"For A Complete Donor List Type 'List'\n ") donor_list = [] #create a unique list of donor names for donor in donors: name = donor[0] donor_list.append(name) while True: donor_name = input("What donor(s) are you looking for?\n ").title() if donor_name == 'List': print('\n',"Here is A Complete List of Donor Names\n ") print(donor_list) else: break #prompt for donation amount amount = float(input("How Much Did This Person Donate?\n ")) #Donor name found in list if donor_name in donor_list: for name in donors: if name[0] == donor_name: name[1].append(amount) print(donors) else: continue #Donor name not found in list else: tup = (donor_name,amount) donors.append(tup) #Write Thank You Note print('Dear {},'.format(donor_name), '\n\nThank you for your show of support and generosity.', ' Your Donation of ${:,.1f} '.format(amount),'will contribute to saving Olympic Marmots', ' in Washington State.',' These Marmota are special and a unique gift to the Olympic ', 'National Park ecosystem.\n', '\nAs a way of saying thank you. ', 'You will be receiving your very own Olympic Marmot t-shirt in the mail!\n\n', 'Sincerely,\n\n', 'The Olympic Marmot Wildlife Foundation\n',sep = '') def create_report(): print('{:<25}{}{:^15}{}{:^15}{}{:^15}'.format('Donor Name','|','Total Given','|','Num Gifts','|','Average Gift')) str_len = len('{:<25}{}{:^15}{}{:^15}{}{:^15}'.format('Donor Name','|','Total Given','|','Num Gifts','|','Average Gift')) print('-' * str_len) def sum_value(donations): item = donations[1] return sum(item) sorted_donations = sorted(donors,key = sum_value, reverse=True) for item in sorted_donations: name = item[0] Total_Given = sum(item[1]) Num_Gift = len(item[1]) Avg_Gift = Total_Given/Num_Gift Total_Given = '{:,.0f}'.format(Total_Given) Avg_Gift = '{:,.0f}'.format(Avg_Gift) print('{:<25}${:^15}{:^15}${:^15}'.format(name,Total_Given,Num_Gift,Avg_Gift)) def exit_from(): print('Work Completed. Good Bye!') sys.exit() def main(): while True: response = input(prompt) if response == "1": send_thanks() elif response == "2": create_report() elif response == "3": exit_from() main()
5919313d0bec108626f9f9b2ae9761bfa9b2dc24
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/gregdevore/lesson02/series.py
2,388
4.34375
4
# Module for Fibonacci series and Lucas numbers # Also includes function for general summation series (specify first two terms) def fibonacci(n): """ Return the nth number in the Fibonacci series (starting from zero index) Parameters: n : integer Number in the Fibonacci series to compute """ # Base cases if n == 0: return 0 elif n == 1: return 1 else: # Recursive case return fibonacci(n-1) + fibonacci(n-2) def lucas(n): """ Return the nth Lucas number (starting from zero index) Parameters: n : integer Lucas number to compute """ # Base cases if n == 0: return 2 elif n == 1: return 1 else: # Recursive case return lucas(n-1) + lucas(n-2) def sum_series(n, n0=0, n1=1): """ Return the nth term in the summation series starting with the terms n0 and n1. If first two terms are not specified, the Fibonacci series is printed by default. Parameters: n : integer The number in the summation series to compute Keyword arguments: n0 : The first term in the series (default 0) n1 : The second term in the series (default 1) """ # Base cases if n == 0: return n0 elif n == 1: return n1 else: # Recursive case return sum_series(n-1, n0, n1) + sum_series(n-2, n0, n1) if __name__ == "__main__": # Run some tests # Fibonacci series # Assert first 10 terms are correct 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 fibonacci(8) == 21 assert fibonacci(9) == 34 # Lucas numbers # Assert first 10 terms are correct assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(2) == 3 assert lucas(3) == 4 assert lucas(4) == 7 assert lucas(5) == 11 assert lucas(6) == 18 assert lucas(7) == 29 assert lucas(8) == 47 assert lucas(9) == 76 # Sum series # Make sure defaults are for Fibonacci series assert sum_series(4) == fibonacci(4) # Make sure entering Lucas number values generates correct term assert sum_series(4, 2, 1) == lucas(4) print("All tests passed")
8f6795905fd16e8ca2ee81542700fbae96e4c9bc
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/anthony_mckeever/lesson1/task2/logic-1.py
1,862
4.03125
4
""" Programming In Python - Lesson 1 Task 2: Puzzles - Logic-1 Code Poet: Anthony McKeever Date: 07/20/2019 """ # Logic-1 > cigar_party def cigar_party(cigars, is_weekend): if is_weekend: return cigars >= 40 # range(start, end) uses inclusive start and exclusive end. return cigars in range(40, 61) # Logic-1 > date_fashion def date_fashion(you, date): if you <= 2 or date <= 2: return 0 elif you >= 8 or date >= 8: return 2 else: return 1 # Logic-1 > squirrel_play def squirrel_play(temp, is_summer): if is_summer: return temp in range(60, 101) return temp in range(60, 91) # Logic-1 > caught_speeding def caught_speeding(speed, is_birthday): if is_birthday: if speed <= 65: return 0 elif speed <= 85: return 1 else: return 2 elif speed > 60: if speed <= 80: return 1 else: return 2 else: return 0 # Logic-1 > sorta_sum def sorta_sum(a, b): total = a + b if total in range(10, 20): return 20 return total # Logic-1 > alarm_clock def alarm_clock(day, vacation): weekend = day in [0, 6] if vacation: if weekend: return "off" return "10:00" if not vacation: if weekend: return "10:00" return "7:00" # Logic-1 > love6 def love6(a, b): if a == 6 or b == 6: return True elif a + b == 6: return True elif a - b == 6: return True elif b - a == 6: return True return False # Logic-1 > in1to10 def in1to10(n, outside_mode): if outside_mode: return n not in range(2, 10) elif n in range(1, 11): return True return False # Logic-1 > near_ten def near_ten(num): mod = num % 10 return mod <= 2 or mod >= 8
daecc28f839ba38ce37e3e98b191fd0d21c35c19
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mark-l-taylor/lesson05/mailroom.py
4,689
4.21875
4
#!/usr/bin/env python3 """ Mailroom Program Part 1 The Last Laugh Program https://simpsons.fandom.com/wiki/Last_Laugh_Program """ import datetime def get_donor_names(): """Generate a list of donors.""" return donors.keys() def add_donation(name): """Prompt user for donation and add to donor data.""" while True: amount = input('Enter donation amount in dollars: ') try: # convert the amount to a float and add to donor donors[name].append(float(amount)) except ValueError: print('Value must be a number!') else: return amount def generate_email(name, amount): """Generate email thanking the donation.""" email = '\n'.join(['', 'Dear {},'.format(name), '', 'Thank you for your generous donation of ${:.2f}.'.format(float(amount)), 'Your donation will continue to allow us to put a smile on our patients faces.', '', 'Sincerely,', 'The Last Laugh Program']) return email def send_thanks(): """Generate a thank you note. """ # Prompt for name to send thank you name = input('\nWho would you like to send a thank you to?\n(Tip: type \'list\' for possible names)\n') if name == 'list': print('Current Donors:') for d in get_donor_names(): print(d) # Repeat question for donor email send_thanks() elif name.lower() == 'quit': print('Returning to main menu.') return else: if name not in get_donor_names(): print('\n{} is a new donor! Adding to donor database.'.format(name)) # Add new donor with empty donation donors[name] = [] amount = add_donation(name) print(generate_email(name, amount)) def letters_all(): """Generate letters to each donor""" print('\nGenerating donations letters:') date = datetime.date.today().isoformat() for name, donations in donors.items(): filename = name.replace(' ', '_') + f'_{date}' + '.txt' print(f'{name:20} --> {filename}') with open(filename, 'w') as outf: outf.writelines(generate_email(name, donations[-1])) def donation_sort(data): """ Sort the report data by the total given.""" # Report data is a list: [name, total given, num donations, avg donation] # Sorting on the total given return data[1] def create_report(): """ Create a formatted report of the donor data.""" frmt_header = '{:<26}|{:^13}|{:^11}|{:>13}' frmt_line = '{:<26} ${:>11.2f} {:>11} ${:>12.2f}' print('\nDonations Summary:\n') print(frmt_header.format('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')) print('-' * 66) # Convert the donor data into report form, using list comprehension fmt_data = [[d, sum(donors[d]), len(donors[d]), sum(donors[d]) / len(donors[d])] for d in donors] # Sort the data by the total amount given fmt_data.sort(key=donation_sort, reverse=True) # Print the sorted data in the report format for f in fmt_data: print(frmt_line.format(*f)) def quit_program(): """Quit the program""" print('Exiting Script.') exit() def prompt_actions(): """ Prompt user for action they would like to perform""" print('\nWhat would you like to do?') # Simplify the input to prompt for a numbered response # Create a dictionary from an enumerated list enumerate_actions = dict(enumerate(main_actions.keys(), start=1)) for i, act in enumerate_actions.items(): print(f'\t({i}) {act}') # Get user action response = input('Please select an action: ') while True: try: return int(response), enumerate_actions[int(response)] except ValueError: response = input(f'Select a number between 1 and {len(main_actions)}: ') # # Main Action (Dictionary Switch # main_actions = {'Send thank you to single donor': send_thanks, 'Create report': create_report, 'Send letters to all donors': letters_all, 'Quit': quit_program, } # # Data Set # donors = {'Homer Simpson': [25.15], 'Charles Burns': [0.01, 0.05], 'Kent Brockman': [105.75, 225.76, 387.90], 'Ned Flanders': [1054.85, 2345.00, 876.50], 'Barney Gumble': [15.25, 35.75, 12.99], } if __name__ == '__main__': # Begin the script by asking the user what they want to do # program will continue to loop until the user selects the Quit option while True: resp_num, resp_str = prompt_actions() main_actions.get(resp_str)()
d9a0ff4f9fac9f83291723dfbfd8f010c51e5d3e
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/anthony_mckeever/lesson4/exercise_1/dict_lab.py
1,660
4.28125
4
#!/usr/bin/env python3 """ Programming In Python - Lesson 4 Exercise 1: Dictionary (and Set) Lab Code Poet: Anthony McKeever Start Date: 08/05/2019 End Date: 08/05/2019 """ # Task 1 - Dictionaries 1 print("Task 1 - Dictionaries:") fun_dictionary = {"name": "Sophia", "city": "Seattle", "cake": "Marble" } print(fun_dictionary) fun_dictionary.pop("cake") print(fun_dictionary) fun_dictionary.update({"fruit": "Mango"}) print(fun_dictionary.keys()) print(fun_dictionary.values()) has_cake = "cake" in fun_dictionary.keys() has_mango = "Mango" in fun_dictionary.values() print("Has Cake:", has_cake) print("Has Mango:", has_mango) # Task 2 - Dictionaries 2 print("\n\nTask 2 - Dictionaries 2:") fun_dictionary2 = {} for k, v in fun_dictionary.items(): fun_dictionary2.update({k : v.lower().count('t')}) print(fun_dictionary2) # Task 3 - Sets 1 print("\n\nTask 3 - Sets:") s2_list = [] s3_list = [] s4_list = [] for i in range(21): if i % 2 == 0: s2_list.append(i) if i % 3 == 0: s3_list.append(i) if i % 4 == 0: s4_list.append(i) s2 = set(s2_list) s3 = set(s3_list) s4 = set(s4_list) print(s2) print(s3) print(s4) print("s3 is subset of s2:", s3.issubset(s2)) print("s4 is subset of s2:", s4.issubset(s2)) # Task 4 - Sets 2 print("\n\nTask 4 - Sets 2:") python_set = set(['p', 'y', 't', 'h', 'o', 'n']) python_set.update('i') marathon_set = set(["m", "a", "r", "a", "t", "h", "o", "n"]) union_set = python_set.union(marathon_set) intersect_set = python_set.intersection(marathon_set) print("Union Set:", union_set) print("Intersection Set:", intersect_set)
4ec56c9e0719263dda46b5e842e7532f73d81c59
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shervs/lesson04/mailroom2.py
4,022
3.71875
4
#!/usr/bin/env python import sys import string donor_dict = {"William Gates, III": [1.50, 653772.32, 12.17], "Jeff Bezos": [877.33], "Paul Allen": [663.23, 43.87, 1.32], "Mark Zuckerberg": [1663.23, 4300.87, 10432.0], } prompt = "\n".join(("Please choose from below options:", "1 - Send a Thank You", "2 - Create a Report", "3 - Send letters to everyone", "4 - Quit", ">>> ")) def create_report(a_donor_dict): # prints a list of donors, sorted by total #historical donation amount. print("\n".join(('Donor Name | Total Given | Num Gifts | Average Gift', '------------------------------------------------------------------'))) for donor in sorted(a_donor_dict, key=lambda k: sum(a_donor_dict[k]), reverse =True): print('{:26s}'.format(donor),'$', '{:10.2f}'.format(sum(a_donor_dict[donor])), '{:11d}'.format(len(a_donor_dict[donor])), ' $', '{:11.2f}'.format(sum(a_donor_dict[donor])/len(a_donor_dict[donor]))) def donor_exist(a_name, a_donor_dict): # returns true if a donar's name exists in #the database , Flase if not for donor in a_donor_dict: if donor == a_name: return True return False def add_donor(new_donor , a_donor_dict): #adds new donor's name to the database a_donor_dict.update({new_donor: []}) def add_donation(a_donor, a_donor_dict): #takes donation amount from the user for #a given donor, returns donation amount new_donation = input("input donation amount?") for donor in a_donor_dict: if donor == a_donor: donor_dict[donor].append(int(new_donation)) return new_donation def print_donor_list(a_donor_dict): # prints the name of all the donors for donor in a_donor_dict: print(donor, end="\n") def send_thank_you(a_donor_dict): prompt = "\n".join(("Send a thank you note!", "Please type donor's full name or type 'list' to view list of donors", ">>> ")) while True: response = input(prompt).title() # continuously collect user selection # now redirect to feature functions based on the user selection if response == "List": print_donor_list(a_donor_dict) elif not donor_exist(response, a_donor_dict): add_donor(response , a_donor_dict) print(f"Thank you {response} for your generous donation of ${add_donation(response, a_donor_dict)}") break else: print(f"Thank you {response} for your generous donation of ${add_donation(response, a_donor_dict)}") break def Send_letters_to_all(a_donor_dict): for donor in a_donor_dict: #remove punctuation from donor's name and join donor_name = donor.translate(str.maketrans('', '', string.punctuation)).split() message_dict = { 'first':donor_name[0] , 'last':' '.join(donor_name[1:]) ,'total donation':sum(a_donor_dict[donor]) } #write letter to the file with open('_'.join(donor_name)+'.txt', 'w') as f: f.write('''Dear {first} {last},\n Thank you for your donation of ${total donation:.0f} throughout these years.\n Cheers,\n -The team'''.format(**message_dict)) print("\nThank you letters were written into the files!\n") def exit_program(a_donor_dict): print("Bye!") sys.exit() # exit the interactive script def not_valid(a_donor_dict): print('\nNot a valid option!\n') def main(): switch_func_dict = { 1: send_thank_you, 2: create_report, 3: Send_letters_to_all, 4: exit_program } while True: response = int(input(prompt)) # continuously collect user selection # now redirect to feature functions based on the user selection switch_func_dict.get(response,not_valid)(donor_dict) if __name__ == "__main__": main()
c4421469ace088d8a46b1ebc23270d68e497dacc
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chasedullinger/lesson04/trigrams.py
4,742
4.40625
4
#!/usr/bin/env python3 # PY210 Lesson 04 Trigrams - Chase Dullinger import sys import random def read_in_data(filename, header_line=None, end_of_file_line=None): """Reads in filename and returns a list of the lines it contained. :param filename: filename to read in. :param header_line: line that signifies start of data. :param end_of_file_line: line that signifies no further data of use in file :returns lines: List of cleaned up lines from the read in file """ lines = [] in_text_section = False if header_line else True with open(filename, "r") as fn: for line in fn.readlines(): print(line) if line.startswith(end_of_file_line): break if in_text_section: tmp_line = line.rstrip() # Clean up end of line characters if tmp_line: # No need to include empty lines lines.append(tmp_line) if not header_line or line.startswith(header_line): in_text_section = True continue return lines def make_words(lines): """Split a bunch of lines in individual words :param lines: list of strings to split into words :returns words: list of words""" words = [] for line in lines: words.extend(line.split()) return words def build_trigrams(words): """ build up the trigrams dict from the list of words returns a dict with: keys: word pairs values: list of followers """ trigrams = {} for i in range(len(words)-2): # -2 so we don't overrun the end of the list pair = words[i:i + 2] follower = words[i + 2] trigrams.setdefault(tuple(pair), []) trigrams[tuple(pair)].append(follower) return trigrams def get_random_word_pair(trigrams): """Select a random key in the trigram and return it's value (word pair) :param trigram: trigrams dictionary :returns words: list of words from the trigram """ words = random.choice(list(trigrams.keys())) return words def get_random_percentage(percentage=50): """Return true X% of the time""" return random.randrange(100) < percentage def make_sentence(trigrams, max_length=100, min_length=3): """build up a sentence from the trigrams :param trigrams: trigrams dictionary :param max_length: int max number of words in a sentence :param min_length: int min number of words in a sentence :returns sentence: str sentence """ sentence_words = [] seed_words = get_random_word_pair(trigrams) sentence_length = random.randint(min_length, max_length) while len(sentence_words) < sentence_length: if seed_words in trigrams: sentence_words.extend(trigrams[seed_words]) if get_random_percentage(10) \ and not sentence_words[-1].endswith(","): sentence_words.append(",") seed_words = tuple(sentence_words[-2:]) else: seed_words = get_random_word_pair(trigrams) sentence = " ".join(sentence_words) sentence[0].capitalize() # Always need to capitalize the first word if sentence.endswith((",", ".", "?", "!")): sentence = sentence[:-1] # Choose how to end the sentence (i.e. period, ?, or !) if get_random_percentage(80): sentence += "." elif get_random_percentage(50): sentence += "?" else: sentence += "!" return sentence.replace(" ,", ",") # strip off the space ahead of commas def build_text(trigrams, max_sentences=1000, min_sentences=100): """build up a text from sentences created with trigrams :param trigrams: trigrams dictionary (passed to next function) :param max_sentences: int max number of sentences in text :param min_sentences: int min number of sentences in text :returns text: str output text """ sentences = [] text_length = random.randint(min_sentences, max_sentences) while len(sentences) < text_length: sentences.append(make_sentence(trigrams)) if get_random_percentage(20): # Start new paragraph 20% of the time sentences.append("\n") return " ".join(sentences) if __name__ == "__main__": # get the filename from the command line try: filename = sys.argv[1] except IndexError: print("You must pass in a filename") sys.exit(1) header_line = "*** START OF THIS PROJECT GUTENBERG EBOOK" end_of_file_line = "End of the Project Gutenberg EBook" in_data = read_in_data(filename, header_line, end_of_file_line) words = make_words(in_data) word_pairs = build_trigrams(words) new_text = build_text(word_pairs) # print(new_text)
5f0b6d80453356ceab3f1118d39ef4aab4c2cd9c
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/steve-long/lesson01-enviro/activities-exercises/task-2-puzzles/logic2.py
6,282
4.53125
5
# Python210 | Fall 2020 # ---------------------------------------------------------------------------------------- # Lesson01 # Task 2: Puzzles (http://codingbat.com/python) (logic2.py) # Steve Long 2020-09-15 # python /Users/steve/Documents/Project/python/uw_class/python210/lessons/lesson01-enviro/logic2.py # make_bricks: # ------------ # We want to make a row of bricks that is goal inches long. We have a number of small # bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to # make the goal by choosing from the given bricks. This is a little harder than it looks # and can be done without any loops. See also: Introduction to MakeBricks # make_bricks(3, 1, 8) → True # make_bricks(3, 1, 9) → False # make_bricks(3, 2, 10) → True def make_bricks(small, big, goal): result = False if ((goal > ((big * 5) + small)) or ((goal % 5) > small)): # Total number of bricks insufficient or nsufficient number of small bricks for # single big brick. result = False else: # Some other combination will work. result = True return result print("\nmake_bricks:\n") for args in [[3,1,8],[3,1,9],[3,2,10],[5,5,5],[1,4,21],[12,1,4],[36,3,51],[0,1,2],[1,1,7]]: small = args[0] big = args[1] goal = args[2] print("make_bricks({},{},{}) = {}".format(small,big,goal,make_bricks(small,big,goal))) # no_teen_sum: # ------------ # Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- # in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not # count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value # and returns that value fixed for the teen rule. In this way, you avoid repeating the # teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent # level as the main no_teen_sum(). # no_teen_sum(1, 2, 3) → 6 # no_teen_sum(2, 13, 1) → 3 # no_teen_sum(2, 1, 14) → 3 def fix_teen(n): if (((n >= 13) and (n <= 14)) or ((n >= 17) and (n <= 19))): n = 0 return n def no_teen_sum(a, b, c): return (fix_teen(a) + fix_teen(b) + fix_teen(c)) print("\nno_teen_sum:\n") for args in [[1,2,3],[2,13,1],[2,1,14],[1,14,2],[1,15,2],[1,16,2],[1,17,2],[1,19,2],[1,20,2]]: a = args[0] b = args[1] c = args[2] print("no_teen_sum({},{},{}) = {}".format(a,b,c,no_teen_sum(a,b,c))) # make_chocolate: # --------------- # We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and # big bars (5 kilos each). Return the number of small bars to use, assuming we always use # big bars before small bars. Return -1 if it can't be done. # make_chocolate(4, 1, 9) → 4 # make_chocolate(4, 1, 10) → -1 # make_chocolate(4, 1, 7) → 2 def make_chocolate(small, big, goal): smallCount = 0 while (big >= 0): if ((big * 5) <= goal): break else: big -= big smallCount = (goal - (big * 5)) if (smallCount > small): smallCount = -1 return smallCount print("\nmake_chocolate:\n") for args in [[4,1,9],[4,1,10],[4,1,7],[5,5,5],[1,4,21],[12,1,4],[36,3,51],[0,1,2],[1,1,7]]: small = args[0] big = args[1] goal = args[2] print("make_chocolate({},{},{}) = {}".format(small,big,goal,make_chocolate(small,big,goal))) # lone_sum: # ------------ # Given 3 int values, a b c, return their sum. However, if one of the values is the same # as another of the values, it does not count towards the sum. # lone_sum(1, 2, 3) → 6 # lone_sum(3, 2, 3) → 2 # lone_sum(3, 3, 3) → 0 def lone_sum(a, b, c): sum = 0 if ((a != b) and (a != c)): sum += a if ((b != a) and (b != c)): sum += b if ((c != a) and (c != b)): sum += c return sum print("\nlone_sum:\n") for args in [[1,2,3],[3,2,3],[3,3,3],[2,2,3],[1,2,2]]: a = args[0] b = args[1] c = args[2] print("lone_sum({},{},{}) = {}".format(a,b,c,lone_sum(a,b,c))) # round_sum: # ---------- # For this problem, we'll round an int value up to the next multiple of 10 if its # rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the # previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. # Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, # write a separate helper "def round10(num):" and call it 3 times. Write the helper # entirely below and at the same indent level as round_sum(). # round_sum(16, 17, 18) → 60 # round_sum(12, 13, 14) → 30 # round_sum(6, 4, 4) → 10 def round10(num): r = (num % 10) if (r < 5): num = num - r else: num = (num + 10 - r) return num def round_sum(a, b, c): return (round10(a) + round10(b) + round10(c)) print("\nround_sum:\n") for args in [[16,17,18],[12,13,14],[6,4,4],[17,35,51],[111,82,67]]: a = args[0] b = args[1] c = args[2] print("round_sum({},{},{}) = {}".format(a,b,c,round_sum(a,b,c))) # lucky_sum: # ---------- # Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it # does not count towards the sum and values to its right do not count. So for example, if # b is 13, then both b and c do not count. # lucky_sum(1, 2, 3) → 6 # lucky_sum(1, 2, 13) → 3 # lucky_sum(1, 13, 3) → 1 def lucky_sum(a, b, c): sum = 0 n = [a,b,c] for i in range(0,3): if (n[i] == 13): break else: sum += n[i] return sum print("\nlucky_sum:\n") for args in [[1,2,3],[1,2,13],[1,13,3],[13,5,11],[11,33,67]]: a = args[0] b = args[1] c = args[2] print("lucky_sum({},{},{}) = {}".format(a,b,c,lucky_sum(a,b,c))) # close_far: # ---------- # Given three ints, a b c, return True if one of b or c is "close" (differing from a by at # most 1), while the other is "far", differing from both other values by 2 or more. Note: # abs(num) computes the absolute value of a number. # close_far(1, 2, 10) → True # close_far(1, 2, 3) → False # close_far(4, 1, 3) → True def close_far(a, b, c): result = (((abs(a - b) < 2) and ((abs(a - c) > 1) and (abs(b - c) > 1))) \ or ((abs(a - c) < 2) and ((abs(a - b) > 1) and (abs(b - c) > 1)))) return result print("\nclose_far:\n") for args in [[1,2,10],[1,2,3],[4,1,3],[9,8,7],[9,8,6],[9,7,6],[9,6,8],[9,6,7],[6,7,9]]: a = args[0] b = args[1] c = args[2] print("close_far({},{},{}) = {}".format(a,b,c,close_far(a,b,c)))
cf7bd07cc21167bc532182a864a1cad91023a85c
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/gregdevore/lesson08/circle.py
4,436
4.1875
4
#!/usr/bin/env python3 # Circle class from math import pi class Circle(object): def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @property def diameter(self): return self._radius * 2 @radius.setter def radius(self, value): self._radius = value @diameter.setter def diameter(self, value): self._radius = value / 2 @property def area(self): return pi * self._radius ** 2 @classmethod def from_diameter(cls, value): # Construct circle with radius as usual return cls(value / 2) def __str__(self): return 'Circle with radius {:f}'.format(self._radius) def __repr__(self): return 'Circle({:f})'.format(self._radius) def __add__(self, other): if isinstance(other, int): # Adding a constant should produce a circle with the new radius return Circle(self.radius + other) elif isinstance(other, Circle): # Adding two circles should produce a circle with the combined radius return Circle(self.radius + other.radius) else: # Other combinations not supported raise TypeError('unsupported operand type(s) for +: \'Circle\' and \'{}\''.format(type(other).__name__)) def __radd__(self, other): # Reversed addition should follow the same rules return self.__add__(other) def __sub__(self, other): if isinstance(other, int): result = self.radius - other if result <= 0: raise ValueError('Circle radius must be positive.') # Adding a constant should produce a circle with the new radius return Circle(result) elif isinstance(other, Circle): result = self.radius - other.radius if result <= 0: raise ValueError('Circle radius must be positive.') # Adding two circles should produce a circle with the combined radius return Circle(result) else: # Other combinations not supported raise TypeError('unsupported operand type(s) for -: \'Circle\' and \'{}\''.format(type(other).__name__)) def __mul__(self, other): if isinstance(other, int): # Multiplying by a constant should produce a circle with the new radius return Circle(self.radius * other) elif isinstance(other, Circle): # Multiplying two circles should produce a circle with the combined radius return Circle(self.radius * other.radius) else: # Other combinations not supported raise TypeError('unsupported operand type(s) for *: \'Circle\' and \'{}\''.format(type(other).__name__)) def __rmul__(self, other): # Reversed multiplication should follow the same rules return self.__mul__(other) def __truediv__(self, other): if isinstance(other, int): # Dividing by a constant should produce a circle with the new radius return Circle(self.radius / other) elif isinstance(other, Circle): # Dividing two circles should produce a circle with the new radius return Circle(self.radius / other.radius) else: # Other combinations not supported raise TypeError('unsupported operand type(s) for /: \'Circle\' and \'{}\''.format(type(other).__name__)) def __pow__(self, other): if isinstance(other, int): # Dividing by a constant should produce a circle with the new radius return Circle(self.radius ** other) else: # Other combinations not supported raise TypeError('unsupported operand type(s) for /: \'Circle\' and \'{}\''.format(type(other).__name__)) def __lt__(self, other): return self.radius < other.radius def __eq__(self, other): return self.radius == other.radius class Sphere(Circle): # Override area property to compute surface area of sphere (4*pi*r^2) @property def area(self): return 4 * pi * self._radius ** 2 @property def volume(self): return (4/3) * pi * self.radius ** 3 def __str__(self): return 'Sphere with radius {:f}'.format(self._radius) def __repr__(self): return 'Sphere({:f})'.format(self._radius)
53c6c9fdd81da8c640155c8aed01eed2e753b45a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chieu_quach/lesson04/mailroom_part2.py
6,691
3.78125
4
# Author - Chieu Quach # Assignment - Lesson 4 # Exercise - Mailroom Part 2 # Prints list of users from donation_list. # Update new record if username is not found in list # If use dictionary in tuple list, use append or remove to change. import sys global donation_list, len_donation_list donation_list = [{'full name': 'William Gates III', "Amount": 653684.49, "num_gift": "2", "avg_amt": 326892.24}, {'full name': 'Mark Zukerberg', 'Amount': 16396.10, 'num_gift': '3', 'avg_amt': 5465.37}, {'full name': 'Jeff Bezos', 'Amount': 877.33, 'num_gift': '1', 'avg_amt': 877.33}, {'full name': 'Paul Allen', 'Amount': 708.42, 'num_gift': '3', 'avg_amt': 236.14 }] len_donation_list = len(donation_list) prompt = "\n".join(("Welcome to the Mailroom Part 2", "Please choose from below options: ", "1 - Send a Thank You to a single donor", "2 - Create a Report", "3 - Send letters to all donors", "4 - Quit", ">>>")) msg = ( " Dear {}, " "\n\n" "\t" "Thank you for your generous donation of {:5.2f}. " "\n" "\t" "It will be put to very good use. " "\n\n" "\t\t\t" " Sincerely, " "\n" "\t\t\t" " -The Team " "\n\n" ) from operator import * def send_thankyou(): name_found = "" e = 1 # response = input(" Please enter full name ") response = input(" Please enter full name (type 'list' to list report)") #for key, value in donation_list.items(): for value in donation_list: if response == "list": if e == 1: print ("List of Names \n") e = e + 1 list_name = (value['full name'], float(value['Amount']), int(value['num_gift']), float(value['avg_amt'])) print("{:<19} {:14.2f} {:15d}{:=21.2f} ".format(*list_name)) name_found = "list" elif response == value['full name']: print("name found", value['full name']) name_found = "yes" fullname = value['full name'] amount = value['Amount'] giftnum = value ['num_gift'] # keynum = key name = value else: continue if name_found == "yes": nu_amount = float(input(" Please Enter Donation Amount: ")) new_len_list = len(donation_list) + 1 grand_amount = nu_amount + float(amount) gift_tot = int(giftnum) + 1 amount_avg = grand_amount / gift_tot # Update record to reflect new changes made new_list = {"full name": response, "Amount": grand_amount, "num_gift": gift_tot, "avg_amt": amount_avg} # print ("new_list ", new_list) donation_list.remove(name) donation_list.append(new_list) full_name = response # added "_" to last name full_name = ("_".join(full_name.split())) full_name = full_name + ".txt" print(msg.format(response, nu_amount)) # sends text message to output file outfile = open(full_name, "w") cpy = (msg.format(response, nu_amount)) outfile.writelines(cpy) elif name_found == "list": main() else: nu_amount = float(input(" Please Enter Donation Amount: z ")) num_gift = 1 # update new length new_len_list = len(donation_list) + 1 # store name and amount into new_list new_list = {"full name": response, "Amount": nu_amount, "num_gift": num_gift, "avg_amt": nu_amount} # added "_" to last name full_name = ("_".join(response.split())) full_name = full_name + ".txt" #print("msg".format(name_list[0], name_list[1])) print(msg.format(response, nu_amount)) # sends text message to output file outfile = open(full_name, "w") cpy = (msg.format(response, nu_amount)) donation_list.append(new_list) outfile.writelines(cpy) outfile.close() def send_letters(): # reading key and value in list # prints list of letters from donation list for value in donation_list: amount = float(value['Amount']) name = value['full name'] amount = float(value['Amount']) full_name = value['full name'] # added "_" to last name full_name = ("_".join(full_name.split())) full_name = full_name + ".txt" # print ("fullname ", fullname) print(msg.format(name, amount)) outfile = open(full_name, "w") cpy = (msg.format(name, amount)) outfile.writelines(cpy) # print ("cpy ", cpy) outfile.close() def create_report(): name_header = " Donor Name " total_given = " | Total Given |" num_gifts = " Num Gifts | " average_gift = " Average Gift " print ("{:15} {:15} {:15} {:15}" .format(name_header, total_given, num_gifts, average_gift)) print (" ------------------------------------------------------------------------") # reading key and value in list newlist = sorted(donation_list, key=itemgetter('Amount'), reverse=True) # for key,value in sorted(donation_list.items()): # for key, value in sorted(donation_list.items(), key=lambda item: item[0]): for value in newlist: list_name = (value['full name'], float(value['Amount']), int(value['num_gift']), float(value['avg_amt'])) print("{:<19} {:14.2f} {:15d}{:=21.2f} ".format(*list_name)) print ("\n\n\n") def exit_program(): print ("Thanks for visiting ") sys.exit() def main(): while True: # Use switch case to call functions from user input switch = {1: send_thankyou, 2: create_report, 3: send_letters, 4: exit_program, } response = input(prompt) response = int(response) if response in switch: switch[response]() else: print ("Invalid input ") # Main function if __name__ == "__main__": main()
a745d05e6a02ef1dcbf8e66aff92ad23dda0e30f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jason_jenkins/lesson04/trigrams.py
2,038
4.3125
4
#!/usr/bin/env python3 """ Lesson 4: Trigram assignment Course: UW PY210 Author: Jason Jenkins Notes: - Requires valid input (Error checking not implemented) - Future iteration should focus on formating input -- Strip out punctuation? -- Remove capitalization? -- Create paragraphs? """ import random import sys def build_trigram(words): """ build up the trigrams dict from the list of words """ trigrams = dict() for i in range(len(words) - 2): pair = tuple(words[i:i + 2]) follower = words[i + 2] if(pair in trigrams): trigrams[pair].append(follower) else: trigrams[pair] = [follower] # build up the dict here! return trigrams def make_words(text): """ Splits a long string of text into an list of words """ return text.split() def build_text(word_pairs, iterations=100000): """ Creates new text from a trigram """ text_list = [] # Create the start of the text first_two = random.choice(list(word_pairs.keys())) text_list.append(first_two[0]) text_list.append(first_two[1]) text_list.append(random.choice(word_pairs[first_two])) # Iterate to create a long text stream for i in range(iterations): last_two = tuple(text_list[-2:]) if last_two in word_pairs: text_list.append(random.choice(word_pairs[last_two])) return " ".join(text_list) def read_in_data(filename): """ Reads in text from a file """ try: with open(filename, 'r') as f: return f.read() except FileNotFoundError: print("File not found") sys.exit(1) if __name__ == "__main__": # get the filename from the command line try: filename = sys.argv[1] except IndexError: print("You must pass in a valid filename") sys.exit(1) in_data = read_in_data(filename) words = make_words(in_data) word_pairs = build_trigram(words) new_text = build_text(word_pairs) print(new_text)
6f5a61cf17281a202ca28d43e110d25235a76334
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/nam_vo/lesson02/fizz_buzz.py
445
4.1875
4
# Loop thru each number from 1 to 100 for number in range(1, 101): # Print "FizzBuzz" for multiples of both three and five if (number % 3 == 0) and (number % 5 == 0): print('FizzBuzz') # Print "Fizz" for multiples of three elif number % 3 == 0: print('Fizz') # Print "Buzz" for multiples of five elif number % 5 == 0: print('Buzz') # Print number otherwise else: print(number)
117f419383bf9738105c14d90bfaa42acf0c9c9c
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Ajay_Randhawa/lesson04/Trigrams.py
2,420
4
4
#!/usr/bin/env python3 import random import itertools import string import re #words = ['I', 'wish', 'I', 'may', 'I', 'wish', 'I', 'might', 'I', 'wish', 'might', 'wish'] def build_trigrams(words): """ build up the trigrams dict from the list of words returns a dict with: keys: word pairs values: list of followers """ trigrams = {} for i in range(len(words)-2): curr_word = words[i] next_word = words[i+1] next1_word = words[i+2] key = (curr_word, next_word) if key in trigrams: trigrams[key].append(next1_word) else: trigrams[key] = [next1_word] #print(trigrams) return trigrams def build_text(word_pairs): ''' returns new text using the trigrams dict starts with a known pair. checks if the known pair equals an existing dict key and adds the value to list else it find a random pair to keep going ''' l = [] a = list(word_pairs.keys()) a = a[:1] for x, y in a: l.append(x) l.append(y) a = list(word_pairs.keys()) for key, values in word_pairs.items(): if key[0] == l[-2] and key[1] == l[-1]: z = random.randint(1,2) try: l.append(values[0]) except IndexError: l.append(values[0]) else: random_entry = random.choice(a) random_entry = random_entry[:2] l.append(random_entry[0]) l.append(random_entry[1]) l.append('......TO BE CONTINUED.') l = " ".join(l) return l def read_in_data(filename): ''' reads a text file and returns a list of words skips the first 62 lines ''' a = [] with open(filename, 'r') as g: for _ in range(62): next(g) for line in g: words = line.split() #convert to lower case words = [word.lower() for word in words] #translate each word to remove the punctuation table = str.maketrans('', '', string.punctuation) stripped = [w.translate(table) for w in words] a.append(stripped) a = list(itertools.chain.from_iterable(a)) return a if __name__ == "__main__": words = read_in_data('sherlock.txt') trigrams = build_trigrams(words) new_text = build_text(trigrams) print(new_text)
b1931b9b7bc509fb729d601f35cfc148784b3638
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shodges/lesson08/circle.py
3,080
3.90625
4
#!/usr/bin/env python3 import math class Circle(object): def __init__(self, radius): try: self._radius = float(radius) self._diameter = float(radius) * 2 except ValueError: raise TypeError("radius expects a float") def __str__(self): return 'Circle with radius {:.5f}'.format(self._radius) def __repr__(self): return '{}({})'.format(self.__class__.__name__, self._radius) def __add__(self, other): try: return self.__class__(self._radius + other._radius) except AttributeError: return self.__class__(self._radius + other) def __radd__(self, other): return self.__add__(other) def __sub__(self, other): try: return self.__class__(self._radius - other._radius) except AttributeError: return self.__class__(self._radius - other) def __rsub__(self, other): return self.__class__(other - self._radius) def __mul__(self, other): try: return self.__class__(self._radius * other._radius) except AttributeError: return self.__class__(self._radius * other) def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): try: return self.__class__(self._radius / other._radius) except AttributeError: return self.__class__(self._radius / other) def __rtruediv__(self, other): return self.__class__(other / self._radius) def __lt__(self, other): return self._radius < other._radius def __gt__(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 __eq__(self, other): return self._radius == other._radius def __ne__(self, other): return self._radius != other._radius @property def radius(self): return self._radius @property def diameter(self): return self._diameter @property def area(self): return math.pow(self._radius, 2) * math.pi @classmethod def from_diameter(cls, value): return cls(value / 2) @radius.setter def radius(self, value): try: self._radius = float(value) self._diameter = float(value) * 2 except ValueError: raise TypeError("radius expects a float") @diameter.setter def diameter(self, value): try: self._radius = float(value) / 2 self._diameter = float(value) except ValueError: raise TypeError("radius expects a float") class Sphere(Circle): def __str__(self): return 'Sphere with radius {:.5f}'.format(self._radius) @property def area(self): return 4 * math.pow(self._radius, 2) * math.pi @property def volume(self): return (4/3) * math.pow(self._radius, 3) * math.pi
0ccb3742f5f6bc680207c82d952d102f7125e36f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/annguan/lesson02/fizz_buzz.py
524
4.375
4
#Lesson 2 Fizz Buzz Exercise #Run program "FizzBuzz()" def fizz_buzz(): """fizz_buzz prints the numbers from 1 to 100 inclusive: for multiples of three print Fizz; for multiples of five print Buzz for numbers which are multiples of both three and Five, print FizzBuzz """ for i in range (1,101): if i % 3 == 0 and i % 5 ==0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)
cb6b3ec734e2a48ed3ff64f64b58118d9b73f8de
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Lina/Lesson9/cli_main.py
6,321
3.921875
4
#! python #---------------------------------------------------- # Lesson 9 - Assignment 8: Mailroom - Object Oriented # User interface cli_main.py #---------------------------------------------------- import sys from donor_models import Donor, DonorCollection from operator import itemgetter from datetime import date dc = DonorCollection() def menu_selection(prompt, dispatch): #This function will ask the user to choose an option from the menu, #and call the associated function in the dispatch dictionary. while True: response = input(prompt) if response in dispatch: dispatch[response]() else: print("That is not a valid option!") def send_a_thank_you(): #This function will first prompt user for a donor's name, or type list to see #all donors. After a name is entered, it will prompt for a donation amount to #be added. At the end, a 'Thank You' letter will go out to the donor. The user #may choose to quit at anytime by typing 'q' at the prompt, and it will take #the user back to the main menu. For now, the letter will print to the terminal. prompts = {1 : "Please enter first and last name or type 'list' to see all donors or q to quit:", 2 : "Name contains invalid character(s), please try again:", 3 : "Please enter first and last name only:", 5 : "Please enter a donation amount or q to quit:", 6 : "Please enter a valid amount greater than zero or q to quit:", 7 : "Amount cannot have more than two decimal places, please try again:", 8 : "Is the amount {:.2f} correct? (Y/N)", 9 : "Invalid response, please re-enter the donation amount or q to quit:" } symbol = ">>>" #Asks user to enter a donor name name_list = dc.donor_list() prompt = prompts[1] while True: in_prompt = "\n".join((prompt, symbol)) name = input(in_prompt) if name == 'list': print("\n".join(name_list)) continue elif name == "q": return else: prompt_num, name = check_input_name(name, name_list) if prompt_num > 0: #invalid input prompt = prompts[prompt_num] continue else: break #Asks user to enter a donation amount prompt = prompts[5] while True: in_prompt = "\n".join((prompt, symbol,)) amount = input(in_prompt) if amount == "q": return try: amount = float(amount) except ValueError: prompt = prompts[6] continue else: if amount <= 0: prompt = prompts[6] continue elif str(amount)[::-1].find('.') > 2: prompt = prompts[7] continue else: #ask user to confirm the amount in_prompt = "\n".join((prompts[8], symbol)).format(amount) response = input(in_prompt) if response.lower() == "n": prompt = prompts[5] continue elif response.lower() == "y": break elif response == "q": return else: prompt = prompts[9] continue dc.add_donation(name, amount) d = Donor(name) print(d.thank_you_letter(d.first_name, amount)) def check_input_name(name, name_list): #Checks if the name is acceptable. #If the name is in the name_list, returns that name so that it can match #the 'database' when adding a donation. #For new name, capitalize the first character of first and last name # (it does not capitalize the letter after the dash) prompt_num = 0 new_name = name name = " ".join(name.split()) #remove any excessive spaces words = name.split() if len(words) > 2: prompt_num = 3 elif len(words) < 2: prompt_num = 1 else: name_from_list = [donor for donor in name_list if donor.lower() == name.lower()] if name_from_list: new_name = name_from_list[0] elif all_valid_chars(words[0]) and all_valid_chars(words[1]): new_name = words[0].capitalize() + " " + words[1].capitalize() else: prompt_num = 2 return prompt_num, new_name def all_valid_chars(word): #Dash is the only valid non-alpha and it cannot have more than one if word.isalpha(): valid = True elif word.count("-") == 0: #dash is the only valid non-alpha valid = False elif word.count("-") == 1 and word[0] != "-" and word[-1:] != "-": valid = True else: valid = False #too many dashes or dash is in unexpected location return valid def create_a_report(): #Gets the report from DonorCollection class and prints to the terminal. #It will show in the order of total donation amount from highest to lowest. print(dc.donors_summary_report()) print() def send_letters_to_all_donors(): #Writes a letter to each donor into a file, and the file will be #created in the directory that the program is running on. letters = dc.letters_to_all_donors() for letter in letters: filename = letter[1].replace(" ", "_") + ".txt" #use donor name for filename with open(filename, 'w') as out_file: out_file.write(letter[0]) def exit_program(): print("Exiting the Mailroom program...") sys.exit() # exit the interactive script def main(): #Calls the menu_selection to prompt user to choose a task from the menu prompt = "\n".join(("Welcome to the ChangeALife Mailroom!", "Please choose from below options:", "1 - Send a Thank You to a donor", "2 - Create a Report", "3 - Send letters to all donors", "4 - Exit", ">>> ")) dispatch = {"1" : send_a_thank_you, "2" : create_a_report, "3" : send_letters_to_all_donors, "4" : exit_program } menu_selection(prompt, dispatch) if __name__ == "__main__": main()
93d741a687818c77a85d81c5835390dd87707ad3
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/IanMayther/mailroom/Mailroom.py
4,468
3.671875
4
#!/usr/bin/env python3 import pathlib import io import os from collections import defaultdict, namedtuple #Donors donors = {"Morgan Stanely": [0.01, 20.00], "Cornelius Vanderbilt": [800, 15, 10.00], "John D. Rockefeller": [7000, 150.00, 25], "Stephen Girard": [60000], "Andrew Carnegie": [0.04, 999.99],} #Single Thank You def receiver(): viable_ans = False while viable_ans == False: new_vs_ex = input("Donor Name, List, Quit? ") name = new_vs_ex if new_vs_ex.lower() == "quit": name = "quit" viable_ans = True elif new_vs_ex.lower() == "list": don_list = donor_list() don_num = int(input("Select # above: ")) name = don_list[don_num-1] if new_vs_ex.lower() != "quit": donation_value = input("What is the value of the donation? ") if donation_value.lower() == "quit": name = "quit" viable_ans = True elif isinstance(gift(donation_value), float): viable_ans = True if new_donor(name): donors[name].append(gift(donation_value)) viable_ans = True else: donors[name] = [gift(donation_value)] viable_ans = True don_val = sum(donors[name]) print("\n" + thank_you(name, don_val)) return name #Donor List def donor_list(): i = 1 temp_list = [key for key in sorted(donors.keys())] for key in sorted(donors): print(f"[{i}] - {key}") i += 1 return temp_list #New Donor def new_donor(name): if name not in donors: name_of_new = False else: name_of_new = True return name_of_new #Get Value of Donation def gift(donation): if isinstance(donation, float): value = donation else: while True: try: value = float(donation) break except ValueError: raise ValueError() return value #Print Thank you def thank_you(to_donor, gift_amount): body = f"Thanks {to_donor} for your ${round(gift_amount,2)} in donations." return body #Print Email def email(to_donor, gift_amount): name = to_donor donation = gift_amount body = f"""Greetings {name}\n \n Thank you so much for your generous contribution to our charity.\n It is donors like you who make our work of building schools for ants' possible.\n With your gift of ${donation}, means (10) or (20) more schools can be built to help the ants learn to read.\n \n Sincerely,\n Derek Zoolander\n Founder and C.E.O. of Derek Zoolander Charity for Ants Who Can't Read Good (DZCAWCRG)\n""" return body def calc_report(my_dict): new_dict = {k: [sum(v), len(v), sum(v)/len(v)] for k, v in sorted(my_dict.items())} calc_dict = sorted(new_dict.items(), key=lambda t: t[1], reverse=True) return calc_dict def print_report(): #Header print("\n") print("{0:<25s}|{1:^15s}|{2:^15s}|{3:>12s}".format("Donor Name", "Total Given", "# of Gifts","Avg. Gift")) print("-" * 72) for k in calc_report(donors): print("{0:<25s}${1:>14.2f}{2:>17d} ${3:>11.2f}".format(k[0], k[1][0], k[1][1], k[1][2], end ='')) print("\n") return #Send Letter def send_letter(): path = pathlib.Path.cwd() / 'mailroom' for k, v in donors.items(): file_name = k + '_Thank you Letter.txt' with open(os.path.join(path, file_name), 'w') as l: l.write(email(k, sum(v))) print(f"Sending Letters to disk: {path}\n") pass #Quit def quit(): print("Quitting, Thank you.") return "quit" #Main Menu Options def main_menu(prompt, dict_choice): while True: choice = input(prompt) #Try to handle non-list selections try: if dict_choice[choice]() == "quit": break except KeyError: print("Please enter a number from the list.") choice_menu = ("Choose an Action:\n" "\n" "1 - Send Thank You to Single Donor.\n" "2 - Create Report.\n" "3 - Send Letters to ALL Donor.\n" "4 - Quit.\n") main_selections = {"1" : receiver, "2" : print_report, "3" : send_letter, "4" : quit, } #Main Exicutable if __name__ == '__main__': main_menu(choice_menu, main_selections)
f42ce9596c045c68fa4c5b0209ed27a3e4c8f38f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/N0vA/lesson_09/cli_main.py
2,359
3.609375
4
#!/usr/bin/env python from donor_models import * import sys donors = {'Bill Gates': Donor('Bill Gates', [2000000, 250000000]), 'Jeff Bezos': Donor('Jeff Bezos', [2000000]), 'Elon Musk': Donor('Elon Musk', [50000000, 10000000]), 'Howard Schultz': Donor('Howard Schultz', [1000000]), 'Paul Allen': Donor('Paul Allen',[450000000])} database = DonorCollection(**donors) def donation_amount(name): # User inputs donation # Enter donation amount while True: try: amount = int(input('How much was their donations? ')) except ValueError: print('Sorry that is an invalid') continue else: break return amount def thank_you(): # Send a thank you # Set up inputs for appending database name = 'list' while name == 'list': name = input("Alright. Which donor would you like to send a thank you card?\nType 'list' to see a list of past donors >>>") if name == 'list': print(list(donors.keys())) donation = donation_amount(name) # Add new donation to database if database._database.get(name): database._database.get(name).add_donation(donation) else: database.add_donor(name, donation) # Print thank you email print(database._database.get(name).text_thank_you()) def report(): """Print a report of the existing donors""" database.display_report() # Exit to main menu exit = 'none' while exit != 'quit': exit = input('Type quit to return to the menu... ') # Execute file when running if __name__ == '__main__': arg_dict = {'1': thank_you, '2': report, '3': exit} while True: # Opens up the mailroom task = 0 task = input("\n".join(("What do you need to do?", "Please choose from the options below:", "1 - Send Thank You Card", "2 - Print A Report", "3 - Exit", ">>> "))) # Run functions for tasks based on user's response while True: try: arg_dict.get(task)() except (ValueError, TypeError, KeyError) as e: task = input('Please enter a valid option from 1-3: ') continue else: break
dfded6161f67b76fac8ff7fd0893496e81e4f4c4
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/lisa_ferrier/lesson05/comprehension_lab.py
1,532
4.53125
5
#!/usr/bin/env python # comprehension_lab.py # Lisa Ferrier, Python 210, Lesson 05 # count even numbers using a list comprehension def count_evens(nums): ct_evens = len([num for num in nums if num % 2 == 0]) return ct_evens food_prefs = {"name": "Chris", "city": "Seattle", "cake": "chocolate", "fruit": "mango", "salad": "greek", "pasta": "lasagna"} # 1 .Using the string format method, read food_prefs as a sentence. food_prefs_string = "{name} is from {city} and he likes {cake} cake, {fruit} fruit, {salad} salad, and {pasta} pasta.".format(**food_prefs) # 2 Using a list comprehension,build a dictionary of numbers from zero to fifteen and the hexadecimal equivalent num_list = [(n, hex(n)) for n in list(range(0, 16))] # 3 Same as before, but using a dict comprehension. num_list = {n: hex(n) for n in range(0, 16)} # 4 Make a new dict with same keys but with the number of a's in each value food_prefsa = {(k, v.count('a')) for k, v in food_prefs.items()} # 5 Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible 2, 3 and 4 # 5a Do this with one set comprehension for each set. s2 = {n for n in list(range(0, 21)) if n % 2 == 0} s3 = {n for n in list(range(0, 21)) if n % 3 == 0} s4 = {n for n in list(range(0, 21)) if n % 4 == 0} # 5c create sets using nested set comprehension on one line: nums = list(range(0, 21)) divisors = [2, 3, 4, 5] divisor_sets = [{n for n in nums if n % d == 0} for d in divisors]
16a17d11e32521f8465723d8a72354833bcd84e1
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Shweta/Lesson08/test_circle.py
1,762
4.1875
4
#!/usr/bin/env python #test code for circle assignment from circle import * #######1- test if object can be made and returns the right radius or not#### def test_circle_object(): c=Circle(5) assert c.radius == 5 def test_cal_diameter(): c=Circle(5) #diameter=c.cal_diameter(5) assert c.diameter == 10 def test_set_diamter(): c=Circle(10) c.diameter=20 assert c.diameter == 20 assert c.radius == 10 def test_area(): c=Circle(2) assert c.area == 12.566370614359172 try: c.area=42 except AttributeError: print("Can not set value for area") def test_from_diameter(): c=Circle.from_diameter(8) assert c.radius == 4 assert c.diameter == 8 def test_str_repr(): c=Circle(8) assert str(c) == "Circle with radius:8" assert repr(c) == "'Circle(8)'" def test_add_mul(): c1 = Circle(2) c2 = Circle(4) assert (c1 + c2).radius == 6 assert (c1 * 4).radius == 8 def test_lt_eq(): c1=Circle(3) c2=Circle(8) assert (c1 > c2) == False assert (c1 == c2) == False assert (c1 < c2) == True c3=Circle(8) assert (c2 == c3) == True def test_sort(): circles=[Circle(18),Circle(16)]#,Circle(4),Circle(11),Circle(30)] circles=sorted(circles) sorted_circle=circles.__str__() assert sorted_circle == "['Circle(16)', 'Circle(18)']"#"['Circle(4)''Circle(11)''Circle(16)''Circle(18)''Circle(30)']" def test_sphere_str(): s=Sphere(3) assert s.radius == 3 assert s.diameter == 6 assert s.area == 113.09733552923255 assert s.volume == 113.09733552923254 def test_sphere_from_diameter(): s=Sphere.from_diameter(12) c=Circle.from_diameter(10) assert s.radius == 6 assert c.radius == 5
c9520adf31b927be371319600a64823bdeed07c2
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jinee_han/lesson04/Trigrams.py
2,380
3.875
4
import random, re, sys def read_and_clean_text(filename): ''' Read and clean text file of unwanted characters :param filename: the relative file name including .txt :return: a list of words ''' file = open(filename, "r") word_collection = [] for line in file: line = line.strip('\n') line = re.sub(r'[^\w\s]',' ',line) for word in line.split(): word_collection.append(word.lower()) return word_collection def build_trigram_dict(words): ''' Build the trigram dictionary from our word list :param words: the word list formed by the given text file :return: a dictionary where key = first two words, value = following word ''' dict_text = dict() for i in range(len(words)-2): dict_key = tuple(words[i:i+2]) follower = words[i + 2] if dict_key in dict_text.keys(): # key and value present in dict val = dict_text[dict_key] val.append(follower) else: list = [follower] dict_element = {dict_key : list} dict_text.update(dict_element) return dict_text def create_text(dict_text, max_length): ''' Create a new corpus based on the dictionary trigram and max allowed length :param dict_text: the trigram dictionary :param max_length: the max allowed length of the story :return: a string of words forming the new story ''' story_list = [] random_key = random.choice(list(dict_text.keys())) story_list.extend([random_key[0], random_key[1]]) val = dict_text[random_key] story_list.append(random.choice(val)) while len(story_list) < max_length: key = tuple(story_list[-2:]) if key in dict_text.keys(): val = dict_text[key] story_list.append(random.choice(val)) else: random_key = random.choice(list(dict_text.keys())) story_list.append(random.choice(dict_text[random_key])) return " ".join(story_list) if __name__ == "__main__": try: filename = sys.argv[1] except IndexError: print("You must pass in a filename!") sys.exit(1) word_collection = read_and_clean_text(filename) dict_text = build_trigram_dict(word_collection) new_text = create_text(dict_text, max_length=250) print(new_text.capitalize())
fa225432cee3d51a93354082556b770c548ea74d
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/csimmons/lesson01/puzzles.py
3,924
3.71875
4
# Warmup-1 Excercise 1 - "Sleep-in" def sleep_in(weekday, vacation): if not weekday or vacation: return True else: return False # Warmup-1 Excercise 2 - "MonkeyTrouble" 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 # Warmup-1 Excercise 3 - "Sum Double" def sum_double(a, b): sum = a + b if a == b: sum = sum * 2 return sum # Warmup-1 Excercise 4 - "Diff21" def diff21(n): if n > 21: return (n - 21) * 2 else: return 21 - n # Warmup-1 Excercise 5 - "Parrot_trouble" def parrot_trouble(talking, hour): if talking and hour < 7: return True if talking and hour > 20: return True return False # Warmup-1 Excercise 6 - "Makes 10" def makes10(a, b): sum = a + b if (a == 10 or b == 10 or sum == 10): return True return False # Warmup-1 Excercise 7 - "near_hundred" def near_hundred(n): if abs(100 - n) <= 10: return True if abs(200 -n) <=10: return True return False # Warmup-1 Excercise 8 - "pos_neg" def pos_neg(a, b, negative): if negative: return (a < 0 and b < 0) else: return ((a < 0 and b > 0) or (a > 0 and b < 0)) # Warmup-1 Excercise 9 - "not_string" def not_string(str): if len(str) >= 3 and str[:3] == 'not': return str return 'not ' + str # Warmup-1 Excercise 10 - "missing_char" def missing_char(str, n): first_part = str[:n] second_part = str[n+1:] return first_part + second_part # Warmup-1 Excercise 11 - "front_back" def front_back(str): if len(str) <= 1: return str x = str[0] y = str[1:-1] z = str[-1] return z + y + x # Warmup-1 Excercise 11 - "front3" def front3(str): if len(str) <= 3: return str * 3 else: front = str[:3] return front * 3 # Warmup-2 Excercise 1 - "string_times" def string_times(str, n): if n < 0: return False return str * n # alt solution: def string_times(str, n): result = '' for i in range(n): return result # Warmup-2 Excercise 2 - "front_times" def front_times(str, n): target = 3 if target > len(str): return str * n return str[:3] * n # alt solution: def front_times(str, n): target = 3 if target > len(str): target = len(str) front = str[:target] result_str = '' for x in range(n): result_str += front return result_str # Warmup-2 Excercise 3 - "string_bits" # N.B. - Since the exercises all use loops, will only code w/ loops going forward def string_bits(str): result_str = '' for bit in range(len(str)): if bit % 2 == 0: result_str += str[bit] return result_str # Warmup-2 Excercise 4 - "string_splosion" # N.B. - Since the exercises all use loops, will only code w/ loops going forward def string_splosion(str): result_str = '' for letter in range(len(str)): result_str += str[:letter+1] return result_str # Warmup-2 Excercise 5 - "last2" def last2(str): if len(str) <= 2: return 0 last2 = str[-2:] count = 0 for i in range(len(str)-2): substring = str[i:i+2] if substring == last2: count = count + 1 return count # Warmup-2 Excercise 6 - "array_count9" def array_count9(nums): count = 0 for num in nums: if num == 9: count = count + 1 return count # Warmup-2 Excercise 7 - "array_front9" def array_front9(nums): end = len(nums) if end > 4: end = 4 for i in range(end): if nums[i] == 9: return True return False # Warmup-2 Excercise 8 - "array123" def array123(nums): for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3: return True return False # Warmup-2 Excercise 9 - "string_match" def string_match(a, b): smaller_str = min(len(a), len(b)) count = 0 for i in range(smaller_str-1): substring_a = a[i:i+2] substring_b = b[i:i+2] if substring_a == substring_b: count = count+1 return count
94d6b57a7d5ea05430442d28f3a8bbf235fa0463
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chris_delapena/lesson02/series.py
1,604
4.40625
4
""" Name: Chris Dela Pena Date: 4/13/20 Class: UW PCE PY210 Assignment: Lesson 2 Exercise 3 "Fibonacci" File name: series.py File summary: Defines functions fibonacci, lucas and sum_series Descripton of functions: fibonacci: returns nth number in Fibonacci sequence, where fib(n)=fib(n-1)+fib(n-2), n(0)=0 and n(1)=1 lucas: returns nth number in Lucas sequence, where luc(n)=luc(n-1)+luc(n-2), n(0)=0 and n(1)=1 sum_series: similar to fibonacci and lucas, except allows user to input optional values for n(0) and n(1) """ def sum_series(n, newPrevious=0, newNext=1): #specify default values for optional args result = 0 previous = newPrevious next = newNext for i in range(n): if i == 0: result = previous; elif i == 1: result = next; else: result = previous + next; previous = next; next = result; return result #return result, not print result def fibonacci(n): result = 0 previous = 0 next = 1 for i in range(n): if i == 0: result = previous; elif i == 1: result = next; else: result = previous + next; previous = next; next = result; return result #return result, not print result def lucas(n): result = 0 previous = 2 next = 1 for i in range(n): if i == 0: result = previous; elif i == 1: result = next; else: result = previous + next; previous = next; next = result; return result
2fc4812861b094c555e241ab3f617402166e4ca9
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/choltzman/lesson03/list.py
1,802
3.9375
4
#!/usr/bin/env python3 def main(): # SERIES ONE fruits = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruits) newfruit = input("Fruit: ") fruits.append(newfruit) print(fruits) idxinput = input("Number: ") # make sure the input is actually a valid number try: idx = int(idxinput) except ValueError: print("Input must be a number!") exit(1) if idx < 1 or idx > len(fruits): print("Bad number!") exit(1) print(fruits[idx-1]) fruits = ['Bananas'] + fruits print(fruits) newfruit2 = input("Fruit: ") fruits.insert(0, newfruit2) print(fruits) for fruit in fruits: if fruit[0].lower() == "p": print(fruit) # SERIES TWO print(fruits) fruits.pop() print(fruits) rmfruit = input("Fruit to Remove: ") for fruit in fruits: if fruit.lower() == rmfruit.lower(): fruits.remove(fruit) print(fruits) # SERIES THREE # fruits.remove(fruit) inside a for loop is a bad idea, it results in # values being skipped in the list. using a second list works around the # problem, but definitely isn't ideal fruits2 = [] for fruit in fruits: while True: userask = input("Do you like {}? (Y/n) ".format(fruit.lower())) if userask.lower() == "n": break elif userask == "y" or userask == "": fruits2.append(fruit) break else: print("Invalid input, must be 'y' or 'n'.") fruits = fruits2 print(fruits) # SERIES FOUR stiurf = [] for fruit in fruits: stiurf.append(fruit[::-1]) fruits.pop() print(fruits) print(stiurf) if __name__ == "__main__": main()
56bdd45d1559dd70939044097d0d235ba9d773fe
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/domdivakaruni/Lesson03/list_lab.py
4,401
4.3125
4
#!/usr/bin/env python3 # Dominic Divakaruni # Lesson03 - List Lab """ Series 1 Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”. Display the list (plain old print() is fine…). Ask the user for another fruit and add it to the end of the list. Display the list. Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). Remember that Python uses zero-based indexing, so you will need to correct. Add another fruit to the beginning of the list using “+” and display the list. Add another fruit to the beginning of the list using insert() and display the list. Display all the fruits that begin with “P”, using a for loop. """ print(" ## Series 1 ## \n\n") fruit = [ "Apples", "Pears", "Oranges", "Peaches" ] #Display the list print("Here's the list of fruit: \n ", fruit, " \n ") #Ask the user for another fruit and add it to the end of the list. Display the list. new = input("Add another fruit to the list:") fruit.append(new) print("Great! Here's the list of fruit \n", fruit, " \n") #Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). item_num = int(input("Use a number to choose a fruit out of the list: ")) if item_num != False: if item_num in range(len(fruit)+1): print("OK! Here's what you choose: \n" + str(item_num) + " -- " + fruit[item_num-1] + "\n") else: print("poor choice try again later! \n") else: print("poor choice try again later \n") continue #Add another fruit to the beginning of the list using + and display the list. fruit = ["Mangoes"] + fruit print("The store now has Mangoes! Here's the list \n", fruit, "\n") #Add another fruit to the beginning of the list using insert() and display the list. fruit.insert(0, "Papayas") print("The store now has Papayas! Here's the list \n\n", fruit) #Display all the fruits that begin with P, using a for loop. for i in fruit: if i[0] == "P": print("here's a fruit in the list that starts with the letter P: ", i) print ("\n") """ Series 2 Using the list created in series 1 above: Display the list. Remove the last fruit from the list. Display the list. Ask the user for a fruit to delete, find it and delete it. (Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.) """ print("## Series 2 ## \n\n") # Display the list. Remove the last fruit from the list. Display the list print("Here's the list of fruit", fruit, "\n\n") series2fruit = list.copy(fruit) series2fruit.pop() print("Removed the last item on the menu. Here's the new list:", series2fruit, "\n\n") #Ask the user for a fruit to delete, find it and delete it. removefruit = input("what fruit would you like to remove from the list:") removefruit if removefruit in fruit: series2fruit.remove(removefruit) print("Here's the list of fruit for Series 2", series2fruit, "\n\n") else: print("poor choice try again later. Here's the list of fruit for Series 2", series2fruit, "\n\n") continue """ Series 3 Again, using the list from series 1: Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list (making the fruit all lowercase). For each “no”, delete that fruit from the list. For any answer that is not “yes” or “no”, prompt the user to answer with one of those two values (a while loop is good here) Display the list. """ series3fruit = list.copy(fruit) print("## Series 3 ## \n\n") length = len(series3fruit) counter =0 while counter < length: rm = input("do you like {}?".format(series3fruit[counter])) if rm == "no": series3fruit.remove(series3fruit[counter]) length -= 1 elif rm == "yes": counter += 1 else: print("Your answer has to be a yes or no") print("Here's the list of fruit for Series 3", series3fruit, "\n\n") """Series 4 Once more, using the list from series 1: Make a new list with the contents of the original, but with all the letters in each item reversed. Delete the last item of the original list. Display the original list and the copy. """ print("## Series 4 ## \n\n") series4fruit = [i[::-1] for i in fruit] fruit.pop() print("Series 1 fruit list:", fruit) print("Series 4 fruit list:", series4fruit)
e7d4ec7612cb74073096e9388581d9d6795e01c2
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/ABirgenheier/lesson06/mailroom_4.py
2,928
3.953125
4
# !/usr/bin/env python3 import sys def donars(): return {'Mike': [200, 150, 50], 'Tony': [150, 50, 250], 'Sarah': [150, 150, 150], } def menu_options(): print("\n".join(("Please select from the following options:", "s - Send a Thank You letter to a single donar.", "c - Create a Report.", "sa - Send letters to all donars.", "q - Quit", " >>> "))) prompt = input('') return prompt.lower() def thank_you_message(donar): message = (f'\nDear {donar},' f'\n\nThank you for your generous donation of ${sum(donars_data.get(donar)):,.2f}.' '\nWe value your contribution and support.' '\n\nSincerely,\n\nNew Horizon Charity Director\n') return message def donations(donar, amount): if donar not in donars_data: donars_data[donar] = [amount] else: donars_data[donar] += [amount] def list_of_donars(): lod = [] for name in donars_data: lod.append(name) return '\n'.join(lod) def send_thank_you(): mail_to = input( "Enter the full name of a donar or 'list' for current donars ") while mail_to.lower() == "list": print(list_of_donars()) mail_to = input("Please enter a full name of a donar ") try: amount = float(input("Enter the donation amount ")) except ValueError: print("\n Amount not valid! Please enter a valid number here! \n") else: donations(mail_to, amount) print(thank_you_message(mail_to)) def summation(arg): return sum(donars_data.get(arg)) def create_report(): header = '\n{:<20}|{:^15}|{:^15}|{:>15}'.format( "Donar Name", "Total Given", "Num Gifts", "Average Gift") print("Donation Report") print(header) print('-'*len(header)) donars_sorted = sorted(donars_data, key=summation, reverse=True) for donar in donars_sorted: total = sum(donars_data.get(donar)) num = len(donars_data.get(donar)) avg = total/num print('{:<20} ${:>14,.2f}{:>14} ${:>16,.2f}'.format( donar, total, num, avg)) print('') def send_letters_to_all(): for donar in donars_data: # print(entry) filename = donar + '.txt' with open(filename, 'w') as f: f.write(thank_you_message(donar)) def quit_now(): print("Good bye and see you next time!") sys.exit() def main(): options_dict = {"s": send_thank_you, "c": create_report, "sa": send_letters_to_all, "q": quit_now} while True: try: option = menu_options() options_dict.get(option)() except TypeError: print("Not a valid option. Please select one of the available options!") if __name__ == "__main__": donars_data = donars() main()
94ffec625e57878ed1f9a0eb7bbfc6effd2af8e6
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mimalvarez_pintor/lesson09/cli_main.py
2,096
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 22 14:00:40 2020 @author: miriam """ import sys from donor_models import Donor from donor_models import DonorCollection donors = DonorCollection.initialize_dict( {'Miriam Pintor': [100, 300], 'Waleed Alvarez': [500, 200, 800], 'Ricardo Gallegos': [50, 75, 100], 'Dina Sayury': [125, 120], 'Urias Gramajo': [1000]}) # Main Menu def options_menu(): print("\n".join(("Please choose from below options:", "1 - Send a Thank You", "2 - Create a Report", "3 - Send Letters to all donors", "4 - Quit" ">>> "))) option = input('') return option def quit_action(): print("Bye") sys.exit() def send_thankyou(): donor_name = input ("Enter the donor's Full Name or 'list' for current" "donors") while donor_name.lower() == "list": print(donors.donors_list()) donor_name = input ("Please enter a FULL Name ") try: donation_amt = float(input ("Enter the Amount for donation ")) except ValueError: print("\n Invalid Amount. Please Enter a valid number \n") else: if donors.donor_exists(donor_name) is False: donor = Donor(donor_name) donors.add(donor) else: donor = donors.donors[donor_name] donor.add_donation(donation_amt) print(donor.print_thanksnote()) def create_report(): """Display a report showing donations.""" donors.create_report() def send_letters_all(): """Generate a letter for each donor in the collection.""" donors.send_letters_all() print('sending Letters to ALL.\n') def main_menu(): switch_dict = {1: send_thankyou, 2: create_report, 3: send_letters_all, 4: quit_action } while True: try: option = int(options_menu()) switch_dict.get(option)() except TypeError: print("\n Invalid Option \n" "Enter a Valid Option from the above list\n") if __name__ == "__main__": main_menu()
4935e41c0a1f707c4d506a34b2148cd022a08b7d
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/cbrown/Lesson 8/circle_class.py
2,133
3.875
4
from functools import total_ordering import math class Circle(object): def __init__(self, radius): self.radius = radius def __str__(self): return f'Circle with radius: {self.radius}' def __repr__(self): return f'Circle({self.radius})' def __add__(self, other): total_radius = self.radius + other.radius return Circle(total_radius) def __rmul__(self, other): return Circle(self.radius * other) def __mul__(self, other): return self.__rmul__(other) @total_ordering def __lt__(self, other): return self.radius < other.radius def __eq__(self, other): return self.radius == other.radius def __le__(self, other): return self.radius <= other.radius @classmethod def from_diameter(cls, diameter): return cls(diameter / 2) def get_diameter(self): self._diameter = self.radius * 2 return self._diameter def set_diameter(self, diameter): self._diameter = diameter self.radius = diameter / 2 diameter = property(get_diameter, set_diameter) def get_area(self): self._area = math.pi * self.radius ** 2 return self._area def set_area(self, value): raise AttributeError("Cannot set the area of the circle") area = property(get_area, set_area) class Sphere(Circle): def __str__(self): return f'Sphere with radius: {self.radius}' def __repr__(self): return f'Sphere({self.radius})' def get_volume(self): self._volume = (4/3) * math.pi * self.radius ** 3 return self._volume def set_volume(self, value): raise AttributeError("Cannot set the volume of the sphere") volume = property(get_volume, set_volume) def get_area(self): self._area = 4 * math.pi * self.radius ** 2 return self._area def set_area(self, value): raise AttributeError("Cannot set the area of the sphere") area = property(get_area, set_area) c1 = Circle(4) c2 = Circle(5) c3 = Circle(6) circle_list = [c3, c1, c2] print(circle_list.sort())
1fe784f7d0d3fb837952fe74e15d8be183f8f90d
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/srmorehouse/Lesson05/mailroom3.py
6,253
4.125
4
#!/usr/bin/env python3 import os import sys """ Steve Morehouse Lesson 05 """ donor_db = {"William Gates, III": [653772.32, 12.17], "Jeff Bezos": [877.33], "Paul Allen": [663.23, 43.87, 1.32], "Mark Zuckerberg": [1663.23, 4300.87, 10432.0] } prompt = "\n".join(("Welcome to the Mailroom!", "Please choose from below options:", "1 - Send a Thank You", "2 - Create Report", "3 - Send letters to all", "4 - Exit", ">>> ")) """ list all donors """ def list_donors (): list = [] for i in donor_db.values(): list.append(i[0]) [print(donor) for donor in donor_db] """ If the user (you) selects “Send a Thank You” option, prompt for a Full Name. If the user types list show them a list of the donor names and re-prompt. If the user types a name not in the list, add that name to the data structure and use it. If the user types a name in the list, use it. Once a name has been selected, prompt for a donation amount. Convert the amount into a number; it is OK at this point for the program to crash if someone types a bogus amount. Add that amount to the donation history of the selected user. Finally, use string formatting to compose an email thanking the donor for their generous donation. Print the email to the terminal and return to the original prompt. It is fine (for now) for the program not to store the names of the new donors that had been added, in other words, to forget new donors once the script quits running. """ def send_a_thank_you (): while True: name = input("Type 'list' to see a list of names or enter a name: ") # now redirect to feature functions based on the user selection if name == "list": list_donors() elif donor_db.get(name) == None: donor_db.update({name: []}) break else: break # enter donation amount donation = float(input("Enter a donation amount: ")) donor_db[name].append (donation) # write email msg = f"\n{name},\n\nThank you for your donation of ${donation}.\n" print(msg) """ If the user (you) selected “Create a Report,” print a list of your donors, sorted by total historical donation amount. Include Donor Name, total donated, number of donations, and average donation amount as values in each row. You do not need to print out all of each donor’s donations, just the summary info. Using string formatting, format the output rows as nicely as possible. The end result should be tabular (values in each column should align with those above and below). After printing this report, return to the original prompt. At any point, the user should be able to quit their current task and return to the original prompt. From the original prompt, the user should be able to quit the script cleanly. Your report should look something like this: Donor Name | Total Given | Num Gifts | Average Gift """ def get_donor_summary(): donor_summary = [] for donor in donor_db.items(): name = donor[0] total_donations = sum(donor[1]) count_donations = len(donor[1]) average_donation = total_donations / count_donations donor_summary.append([name, total_donations, count_donations, average_donation]) return donor_summary """ get_max_lengths """ def get_max_lengths(seq, header): name_len = len(header[0]) total_len = len(header[1]) count_len = len(header[2]) avg_len = len(header[3]) for item in seq: total = f"${item[1]:.02f}" count = str(item[2]) avg = f"${item[3]:.02f}" name_len = len(item[0]) if len(item[0]) > name_len else name_len total_len = len(total) if len(total) > total_len else total_len count_len = len(count) if len(count) > count_len else count_len avg_len = len(avg) if len(avg) > avg_len else avg_len return [name_len, total_len, count_len, avg_len] def sort_key(item): return item[1] """ Return a formatted string that will fit in the donor summary table. """ def format_line(item, lengths): total = f"{item[1]:.02f}" avg = f"{item[3]:.02f}" return f"{item[0]:<{lengths[0]}} ${total:>{lengths[1]}} {item[2]:>{lengths[2]}} ${avg:>{lengths[3]}}" def create_report (): pad = 2 table = [] donor_summary = get_donor_summary() header = ["Donor Name", "Total Given", "Num Gifts", "Average Gift"] lengths = get_max_lengths(donor_summary, header) sep_strings = [("-" * (lengths[0] + pad)), ("-" * (lengths[1] + pad)), ("-" * (lengths[2] + pad)), ("-" * (lengths[3] + pad))] sep_line = "+".join(sep_strings) for item in sorted(donor_summary, key=sort_key, reverse=True): table.append(format_line(item, lengths)) # Header table.insert(0, f"\n{header[0]:<{lengths[0]}} | {header[1]:>{lengths[1]}} | {header[2]:>{lengths[2]}} | {header[3]:>{lengths[3]}} ") table.insert(1, "-" * (len(sep_line) ) ) print("\n".join(table) + "\n") """ Compose the letter to the each donor and write to file """ def print_report (): cur_dir = os.getcwd() for donor in donor_db.items(): name = donor[0] total_donations = sum(donor[1]) count_donations = len(donor[1]) letter = "Thank you {0:s} for your donations totaling ${1:.2f}.".format (name, total_donations) file_name = name.replace(" ","_") + ".txt" full_path = os.path.join (cur_dir,file_name) with open (full_path, "w") as file: file.write (letter) def exit_program(): print("Bye!") sys.exit() # exit the interactive script def main(): prompt_action = {"1" : send_a_thank_you, "2" : create_report, "3" : print_report, "4" : exit_program } while True: response = input(prompt) # continuously collect user selection # now redirect to feature functions based on the user selection try: prompt_action[response]() except KeyError: print ("try again") if __name__ == "__main__": # don't forget this block to guard against your code running automatically if this module is imported main()
b8b02c6cad44ea32423dadfb206994d376d5d90a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/ABirgenheier/lesson03/list.py
3,500
4.375
4
fruits_list = ["pineapple", "zucchini", "apple", "banana", "cucumber", "potato", "lettuce", "salad", "zest", "orange", "jalapino", "yellow_fruit", "star_fruit"] def start_series_one(): _continue = input( "Would you like to add another fruit to the list (y/n)? ") if _continue == "y" or _continue == "Y": series_one_add() else: _search = input( "Would you like to search for a fruit instead? (y/n)? ") if _search == "y" or _search == "Y": series_one_search() else: print("Program ended. Thank you") def series_one_add(): _front_bool = input( "Would you like to insert the fruit to the front or the back of the list? ") if _front_bool == "front" or _front_bool == "Front" or _front_bool == "f" or _front_bool == "F": print(fruits_list) add_fruit = input( "Which fruit would you like to add to the front of the list? ") fruits_list.insert((add_fruit)) print(fruits_list) start_series_one() else: print(fruits_list) add_fruit = input( "Which fruit would you like to add to back of the list? ") fruits_list.append((add_fruit)) print(fruits_list) start_series_one() def series_one_search(): print(fruits_list) _search_method = input( "Please search by index location, or by first letter of fruits name... ") if int(_search_method): if 0 <= int(_search_method) <= len(fruits_list): index = int(_search_method) if fruits_list[index]: print(fruits_list[index]) series_one_search() else: print("Sorry, that fruit index does not exist. Please try again... ") series_one_search() else: print("Sorry, that index is out of the range of the list.") series_one_search() else: print(_search_method[0]) if fruits_list[_search_method[0]]: print(fruits_list[_search_method[0]]) else: print( "Sorry, that first letter of fruit does not exist. Please try again... ") series_one_search() # start_series_one() def series_two(): letter = input( "Please insert letter you wish to find first letter of fruit within contained list (ie: a == apple; b == banana): ") for i in fruits_list: if i[0] == letter: print(i) series_two() # works # series_two() def series_three(): for i in fruits_list: question = input(f"Do you like {i}; 'yes' or 'no'... ") if question.lower() in ("no", "n"): fruits_list.remove(i) print("You don't like {i}... deleted!") print(fruits_list) elif question.lower() in ("yes", "y"): print(f"You like {i}, good to know!") else: print("You didn't follow directions... start again!") series_three() # Works # series_three() def series_four(): i = 0 delete_last = input( "Would you like to delete first and last item from list while we reverse order of all items? ") if delete_last.lower() in ("Yes", "y"): while i < len(fruits_list[1: -1]): print(fruits_list[1 + i][::-1]) i += 1 else: while i < len(fruits_list): print(fruits_list[i][::-1]) i += 1 series_four() series_four()
9b86bcbb40e06c1db91bf2c02167030ade764691
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/amirg/lesson02/fizz_buzz.py
221
3.546875
4
i = 1 while i < 101: x = i % 15 y = i % 5 z = i % 3 if x == 0: print('FizzBuzz') elif y == 0: print('Buzz') elif z == 0: print('Fizz') else: print(i) i += 1
0839a18fd25980bc8d0e31d8d6bcb2652ddb7e9a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/ravi_g/lesson08/test_circle.py
1,775
3.984375
4
#!/usr/bin/env python3 # Testing circle.py import math import circle as cir def test_check_rad_diameter(): ''' checks radius and diameter ''' # initialized with radius 5 c1 = cir.Circle(5) assert c1.radius == 5 assert c1.diameter == 10 # Set diameter c2 = cir.Circle() c2.diameter = 20 assert c2.diameter == 20 assert c2.radius == 10 def test_area(): ''' checks area ''' c3 = cir.Circle(10) assert c3.area == math.pi * 10 ** 2 def test_circle_alter_constructor(): ''' checks from_diameter constructor ''' c4 = cir.Circle().from_diameter(10) assert c4.radius == 5 assert c4.diameter == 10 def test_printing(): ''' test printing ''' c5 = cir.Circle(10) assert repr(c5) == "Circle(10)" assert str(c5) == "Circle with radius 10" def test_circles_numeric_compare_sort(): c6 = cir.Circle(4) c7 = cir.Circle(5) c8 = cir.Circle(5) assert (c6 < c7) is True assert (c6 > c7) is False assert (c7 == c8) is True c8.radius = 5 * 2 assert c8.radius == 10 assert c8.radius == c7.radius + c7.radius assert c8.radius == c7.radius * 2 assert c8.radius == 2 * c7.radius circles = [cir.Circle(6), cir.Circle(7), cir.Circle(5)] assert circles[0].radius == 6 assert circles[1].radius == 7 assert sorted(circles) == [cir.Circle(5), cir.Circle(6), cir.Circle(7)] def test_sphere(): s = cir.Sphere(10) assert s.radius == 10 assert s.diameter == 20 assert s.area == 4 * math.pi * 10 ** 2 assert s.volume == math.pi * pow(10,3) ** (4/3) s2 = cir.Sphere(4) s3 = cir.Sphere.from_diameter(8) assert s2.radius == s3.radius assert s2.area == s3.area assert s3.volume == s2.volume
e34adea7c5453c8145944bfbe6207f8b4801cda8
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kimc05/Lesson03/Slicing_lab.py
1,338
3.9375
4
#sequence to test a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) #function: first and last items exchanged def exchange_first_last(seq): return seq[-1:] + seq[1:-1] + seq[:1] #function: every other item removed removed def alternate_removed(seq): return seq[::2] #function: first 4 and last 4 items removed def dislike_4s(seq): return seq[4:-4] #function: elements reversed def reversed(seq): return seq[::-1] #function: last third, then first, then the middle third in the new order (??????) def thirds_remix(seq): new_s = seq[3:-3] return seq[-3:-2] + seq[2:3] + new_s[2:3] if __name__ == "__main__": # test exchange function assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2) #test alternate removal function assert alternate_removed(a_string) == "ti sasrn" assert alternate_removed(a_tuple) == (2, 13, 5) #test dislike_4s assert dislike_4s(a_string) == " is a st" assert dislike_4s(a_tuple) == () #test reversal function assert reversed(a_string) == "gnirts a si siht" assert reversed(a_tuple) == (32, 5, 12, 13, 54, 2) #test thirds remix function assert thirds_remix(a_string) == "iii" assert thirds_remix(a_tuple) == (12, 13) print("tests passed")
c52e6d2994df1d12a3581a59b1c5a97098d261ed
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jack_anderson/lesson07/html_render.py
3,424
3.96875
4
#!/usr/bin/env python3 """ Jack Anderson 03/01/2020 UW PY210 Lesson 07 A class-based system for rendering html. """ # This is the framework for the base class class Element(object): indent = " " tag = "html" def __init__(self, content=None, **kwargs): self.attribs = dict() for k, v in kwargs.items(): self.attribs[k] = v if content is None: self.contents = [] else: self.contents = [content] def append(self, new_content): self.contents.append(new_content) def render(self, out_file, cur_ind=""): out_file.write(cur_ind) out_file.write(f"<{self.tag}") if len(self.attribs.items()) > 0: for k, v in self.attribs.items(): out_file.write(f' {k}="{v}"') out_file.write(">\n") for content in self.contents: try: content.render(out_file, cur_ind + self.indent) except AttributeError: out_file.write(self.indent + cur_ind) out_file.write(content) out_file.write("\n") out_file.write(cur_ind) out_file.write(f"</{self.tag}>\n") class OneLineTag(Element): def render(self, out_file, cur_ind=""): out_file.write(cur_ind) out_file.write(f"<{self.tag}") for k, v in self.attribs.items(): out_file.write(f' {k}="{v}"') out_file.write(">") for content in self.contents: try: content.render(out_file, cur_ind + self.indent) except AttributeError: out_file.write(content) out_file.write(f"</{self.tag}>") out_file.write("\n") def append(self, new_content): raise NotImplementedError class SelfClosingTag(Element): def render(self, out_file, cur_ind=""): out_file.write(cur_ind) out_file.write(f"<{self.tag}") if len(self.attribs.items()) > 0: for k, v in self.attribs.items(): out_file.write(f' {k}="{v}"') out_file.write(" />\n") def append(self, new_content): raise TypeError class A(OneLineTag): tag = 'a' def __init__(self, link, content): x = link self.attribs = dict() self.attribs['href']= link self.contents = [content] class Title(OneLineTag): tag = 'title' class Hr(SelfClosingTag): tag = 'hr' class Br(SelfClosingTag): tag = 'br' class Body(Element): tag = 'body' class Html(Element): tag = 'html' doc_tag = "<!DOCTYPE html>\n" def render(self, out_file, cur_ind=""): out_file.write(self.doc_tag) Element.render(self, out_file, cur_ind) class P(Element): tag = 'p' class Head(Element): tag = 'head' class Ul(Element): tag = "ul" def __init__(self, **kwargs): self.attribs = dict() self.contents = [] for key, value in kwargs.items(): self.attribs[key] = value def append(self, content): self.contents.append(content) class Li(Element): tag = "li" class H(OneLineTag): def __init__(self, size, content): try: header_size = int(size) except: raise ValueError self.attribs = dict() self.contents = [content] self.tag = f'h{header_size}' class Meta(SelfClosingTag): tag = 'meta'
300cda2ca8204637ec2033f13f77a35248daa77a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jason_jenkins/lesson01/Logic1.py
1,393
3.859375
4
# Lesson 1: Logic1 def cigar_party(cigars, is_weekend): if(is_weekend and cigars >= 40): return True return 40 <= cigars <= 60 def date_fashion(you, date): if you <= 2 or date <= 2: return 0 elif you >= 8 or date >= 8: return 2 else: return 1 def squirrel_play(temp, is_summer): if(temp < 60): return False elif temp <= 90: return True elif is_summer and temp <= 100: return True else: return False def caught_speeding(speed, is_birthday): if is_birthday: speed -= 5 if speed <= 60: return 0 elif speed <= 80: return 1 else: return 2 def sorta_sum(a, b): sum = a + b if 10 <= sum <= 19: return 20 else: return sum def alarm_clock(day, vacation): if day == 6 or day == 0: if vacation: return "off" else: return "10:00" elif vacation: return "10:00" else: return "7:00" def love6(a, b): if a == 6 or b == 6: return True elif a + b == 6: return True elif abs(a - b) == 6: return True else: return False def in1to10(n, outside_mode): if outside_mode: return n <= 1 or n >= 10 else: return 1 <= n <= 10 def near_ten(num): return num % 10 <= 2 or num % 10 >= 8
0ff876263cb8c9e951002b8af261cea3bae6f2ae
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/steve-long/lesson01-enviro/activities-exercises/task-2-puzzles/warmup1.py
7,721
3.859375
4
# Python210 | Fall 2020 # ---------------------------------------------------------------------------------------- # Lesson01 # Task 2: Puzzles (http://codingbat.com/python) (warmup1.py) # Steve Long 2020-09-10 # /Users/steve/Documents/Project/python/uw_class/python210/lessons/lesson01-enviro/warmup1.py # sleep_in # -------- # The parameter weekday is True if it is a weekday, and the parameter vacation is True if # we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True # if we sleep in. # sleep_in(False, False) → True # sleep_in(True, False) → False # sleep_in(False, True) → True def sleep_in(weekday, vacation): return (vacation or (not weekday)) print("\nsleep_in:\n") print("sleep_in({},{}) = {}".format(False,False,sleep_in(False,False))) print("sleep_in({},{}) = {}".format(True,False,sleep_in(True,False))) print("sleep_in({},{}) = {}".format(False,True,sleep_in(False,True))) # diff21: # ------- # Given an int n, return the absolute difference between n and 21, except return double # the absolute difference if n is over 21. # diff21(19) → 2 # diff21(10) → 11 # diff21(21) → 0 def diff21(n): result = abs(21 - n) if (n > 21): result = result * 2 return result print("\ndiff21:\n") print("diff21({}) = {}".format(19,diff21(19))) print("diff21({}) = {}".format(10,diff21(10))) print("diff21({}) = {}".format(21,diff21(21))) print("diff21({}) = {}".format(37,diff21(37))) # near_hundred: # ------------- # Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes # the absolute value of a number. # near_hundred(93) → True # near_hundred(90) → True # near_hundred(89) → False def near_hundred(n): return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10)) print("\nnear_hundred:\n") print("near_hundred({}) = {}".format(93,near_hundred(93))) print("near_hundred({}) = {}".format(90,near_hundred(90))) print("near_hundred({}) = {}".format(89,near_hundred(89))) print("near_hundred({}) = {}".format(190,near_hundred(190))) print("near_hundred({}) = {}".format(210,near_hundred(210))) print("near_hundred({}) = {}".format(211,near_hundred(211))) # missing_char: # ------------- # Given a non-empty string and an int n, return a new string where the char at index n has # been removed. The value of n will be a valid index of a char in the original string # (i.e. n will be in the range 0..len(str)-1 inclusive). # missing_char('kitten', 1) → 'ktten' # missing_char('kitten', 0) → 'itten' # missing_char('kitten', 4) → 'kittn' def missing_char(s, n): return (s[:n] + s[n+1:]) print("\nmissing_char:\n") for sAndN in [["kitten", 1], ["kitten", 0], ["kitten", 4], ["kitten", 5], ["k",0]]: s = sAndN[0] n = sAndN[1] print("missing_char(\"{}\",{}) = \"{}\"".format(s,n,missing_char(s,n))) # monkey_trouble: # --------------- # We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is # smiling. We are in trouble if they are both smiling or if neither of them is smiling. # Return True if we are in trouble. # monkey_trouble(True, True) → True # monkey_trouble(False, False) → True # monkey_trouble(True, False) → False def monkey_trouble(a_smile,b_smile): return (a_smile == b_smile) print("\nmonkey_trouble:\n") for ab_smile in [[True, True], [True, False], [False, False], [False, True]]: a_smile = ab_smile[0] b_smile = ab_smile[1] print("monkey_trouble({},{}) = {}".format(a_smile,b_smile, \ monkey_trouble(a_smile,b_smile))) # parrot_trouble: # --------------- # We have a loud talking parrot. The "hour" parameter is the current hour time in the # range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or # after 20. Return True if we are in trouble. # parrot_trouble(True, 6) → True # parrot_trouble(True, 7) → False # parrot_trouble(False, 6) → False def parrot_trouble(talking, hour): return (talking and ((hour < 7) or (hour > 20))) print("\nparrot_trouble:\n") for talkingHour in [[True, 6], [True, 7], [False, 8], [False, 7], [True, 20], \ [True, 21], [False, 21], [False, 6]]: talking = talkingHour[0] hour = talkingHour[1] print("parrot_trouble({},{}) = {}".format(talking, hour, \ parrot_trouble(talking,hour))) # pos_neg: # -------- # Given 2 int values, return True if one is negative and one is positive. Except if the # parameter "negative" is True, then return True only if both are negative. # pos_neg(1, -1, False) → True # pos_neg(-1, 1, False) → True # pos_neg(-4, -5, True) → True def pos_neg(a, b, negative): result = False if (negative): result = ((a < 0) and (b < 0)) else: result = (((a < 0) and (b >= 0)) or ((a >= 0) and (b < 0))) return result print("\npos_neg:\n") for abn in [[-1,-1,True], [-1,-1,False], [-1,0,True], [-1,0,False], [-1,1,True], \ [-1,1,False], [0,-1,True], [0,-1,False], [0,0,True], [0,0,False], [0,1,True], \ [0,1,False], [1,-1,True], [1,-1,False], [1,0,True], [1,0,False], [1,1,True], [1,1,False]]: a = abn[0] b = abn[1] negative = abn[2] print("pos_neg({}, {}, {}) = {}".format(a, b, negative, \ pos_neg(a, b, negative))) # front_back: # ----------- # Given a string, return a new string where the first and last chars have been exchanged. # front_back('code') → 'eodc' # front_back('a') → 'a' # front_back('ab') → 'ba' # ASSUMPTION: String is pass-by-reference. Return a NEW string. def front_back(s): ns = s.encode().decode() result = ns if (len(ns) > 1): result = (ns[(len(ns) - 1):] + ns[1:(len(ns) - 1)] + ns[0:1]) return result print("\nfront_back:\n") for s in ["code","a","ab","","gold-pressed-latinum"]: print("front_back(\"{}\") = \"{}\"".format(s,front_back(s))) # sum_double: # ----------- # Given two int values, return their sum. Unless the two values are the same, then return # double their sum. # sum_double(1, 2) → 3 # sum_double(3, 2) → 5 # sum_double(2, 2) → 8 def sum_double(a, b): result = a + b if (a == b): result = 2 * result return result print("\nsum_double:\n") for ab in [[1,2],[3,2],[2,2],[0,0],[-7,-8],[47,-47]]: a = ab[0] b = ab[1] print("sum_double({},{}) = {}".format(a,b,sum_double(a,b))) # makes10: # -------- # Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. # makes10(9, 10) → True # makes10(9, 9) → False # makes10(1, 9) → True def makes10(a, b): return ((a == 10) or (b == 10) or ((a + b) == 10)) print("\nmakes10:\n") for ab in [[9,10],[9,9],[1,9],[3,7],[17,-7],[4,5]]: a = ab[0] b = ab[1] print("makes10({},{}) = {}".format(a,b,makes10(a,b))) # not_string: # ----------- # Given a string, return a new string where "not " has been added to the front. However, # if the string already begins with "not", return the string unchanged. # not_string('candy') → 'not candy' # not_string('x') → 'not x' # not_string('not bad') → 'not bad' def not_string(s): result = s if (s[0:3] != "not"): result = ("not " + s) return result print("\nnot_string:\n") for s in ["candy","x","not bad","nottingham","the name of a flavor","head",""]: print("not_string(\"{}\") = \"{}\"".format(s,not_string(s))) # front3: # ------- # Given a string, we'll say that the front is the first 3 chars of the string. If the # string length is less than 3, the front is whatever is there. Return a new string which # is 3 copies of the front. # front3('Java') → 'JavJavJav' # front3('Chocolate') → 'ChoChoCho' # front3('abc') → 'abcabcabc' def front3(s): front = s[:min(3,len(s))] return (front * 3) print("\nfront3:\n") for s in ["Java","Chocolate","601","OT","tactical","Jettison",""]: print("front3(\"{}\") = \"{}\"".format(s,front3(s)))
b5087ee763fb01617c05bfd67ce8185e5f316df5
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/CCSt130/lesson02/has22.py
2,601
3.984375
4
# -*- coding: utf-8 -*- """ This code generates a 1000 element tuple then compares element[n] with element[n+1] to see if there is a match between those elements and a constant. """ """ Lesson02 :: Has22 CodingBat Exercise @author: Chuck Stevens :: CCSt130 Created on Sun Jun 30 21:11:21 2019 """ import random def gen_tuple(): """ Generates ints using PRNG and creates 1000 element tuple. """ # Holds ints from PRNG my_tuple = [] # Counter for while loop ctr0 = 0 # Holds pseudo-random int add_int = None # Generate 1000 pseudo-random ints while (ctr0 <= 999): add_int = (random.randint(1,12)) # Test # print(add_int) # print() # Append ints to tuple my_tuple.append(add_int) # Increment while loop counter ctr0+=1 # Test print() print(my_tuple) print() # Send that tuple back to main return(my_tuple) def has22(a_tuple): """ Compares element[n] to element[n+1] and outputs match to screen. """ # Counters to iterate through the loop ctr1 = 0 ctr2 = 1 # Value that will be searched for in tuple search_val = 2 # Search via loop as long as ctr1 index is less than length of tuple while(ctr1 < len(a_tuple)): # Does the element in the tuple match the search value? if(a_tuple[ctr1] == search_val): print() print("*** Search value '{}' found in tuple. ".format(search_val), end = "") print("Element location is a_tuple[{}] ***".format(ctr1)) # Is the search value found in the subsequent element also? if(a_tuple[ctr1] == a_tuple[ctr2]): print() print(">>> TRUE! Hooray, search value match found! ", end = "") print("Element locations are: ", end = "") print("a_tuple[{}], a_tuple[{}]".format(ctr1,ctr2)) # One could add this match to another list print() # No match between elements else: print() print("Bummer! ", end = "") print("No search value match between: ", end = "") print("a_tuple[{}], a_tuple[{}]".format(ctr1,ctr2)) print() else: pass # Let's increment ctr1+=1 ctr2+=1 if __name__ == "__main__": def main(): # Call function to generate ints my_ints = gen_tuple() # Evaluate elements in tuple has22(my_ints) main()
75c0efba3ab9de62cd3d2e403cc2e5a5bf43d349
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chieu_quach/lesson03/strformat_lab.py
3,327
4.1875
4
# Author : Chieu Quach # Assignment: Lesson03 # Exercise : String Formating Exercise # ============================================= # task 1 def task1(): global file, floatnum, scienum2, scienum3 print ("task 1 ") fnames = [2, 123.4567, 10000, 12345.67] lenfnames = len(fnames) # padded 2 leading 0 print ("file %03d" %fnames[0]) file = "%03d" %fnames[0] print ("float number %3.2f" %fnames[1]) floatnum = "%3.2f" %fnames[1] # print scientifi notation "e" print ("Scientific %2.3e" %fnames[2]) scienum2 = "%2.3e" %fnames[2] # it prints ---> Scientific 1.000e+04 print ("Scientifi 3 %.3e" %fnames[3]) scienum3 = "3 %.3e" %fnames[3] # ============================================= # task 2 # f-string format # ---> use letter f and {} (store variable name inside {}) def task2(): print ("task 2 (f-string format)") print(f"file {file} and float number is {floatnum}.") print(f"scientific notation 2 decimal {scienum2}.") print(f"scientific notation 3 significant figure {scienum3}.") # str.format{} # use {} and .format() # file = "002" # example - print("filename is {} ".format(file)) print ("task 2 (str.format)") print ("file is {} and float number is {} " .format(file,floatnum)) print("scientific notation 2 decimal {} " .format(scienum2)) print("scientific notation 3 significant figure {} " .format(scienum3)) def task3(): print ("task 3 - Build up format strings ") in_tuple = (2,3,5) bracket = "{:d}," merge_bracket = " the {} numbers are : " len_in_tuple = len(in_tuple) i = 0 while i < len_in_tuple: merge_bracket = str(merge_bracket) + bracket i = i + 1 # the [:-1] Removed unwanted "," at end of merge_statement merge_bracket = merge_bracket[:-1] print (merge_bracket.format(len_in_tuple,*in_tuple)) def task4(): # task 4 # Print 5 elements tuple print ("task 4 - 5 element tuple ") in_tuple = (4, 30, 2017, 2, 27) # the *in_tuple would not print any comma # #example - {3:0>2d} is index position 3 (number 2) with padded 0 print (" {3:0>2d} {4} {2} {0:0>2d} {1}".format(*in_tuple)) def task5(): seq = ["orange", 1.3, "lemon", 1.1] onehalf = 1.2 len_seq = len(seq) print ("seq ", seq) for n in range (0,len_seq): tot_onehalf = 0 # check if seq[n] is type float if type(seq[n]) == float: # take argument variable seq[n] * 1.2 seq[n] = onehalf * float(seq[n]) # print items in list in format string print (f"the weight of an {seq[0].upper()} is {seq[1]} and the weight of a {seq[2].upper()} is {seq[3]} ") def task6(): name = ["steve", "jeff", "tim"] age = [15, 24, 34] cost = [100, 1400, 24000] # {:<7} - moves 7 spaces for character string to the left # {:3d} - moves 3 spaces for numeric string to the left print("{:<7} {:<3d} {:3d}".format(name[0], age[0], cost[0])) print("{:<7} {:<3d} {:3d}".format(name[1], age[1], cost[1])) print("{:<7} {:<3d} {:3d}".format(name[2], age[2], cost[2])) # Main function if __name__ == "__main__": task1() task2() task3() task4() task5() task6()
78e78152e2e82208a5f0c7b00a90872aad763734
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/kristoffer_jonson/lesson3/slicing_lab.py
2,089
4.03125
4
def exchange_first_last(seq): """ Return sequence with first and last element flipped :param seq: Requested sequence to be flipped """ return seq[-1:] + seq[1:-1] + seq[:1] def remove_every_other(seq): """ Return sequence with every other element removed. Retains first element. :param seq: Requested sequence to be sliced """ return seq[::2] def remove_four_leading_ending_every_other(seq): """ Return sequence with first 4, last 4 and every other elements removed. :param seq: Requested sequence to be sliced """ return seq[4:-4:2] def reverse_elements(seq): """ Return sequence with elements reversed :param seq: Requested sequence to be flipped """ return seq[::-1] def rotate_thirds(seq): """ Return sequence with the the last third, then first third, then the middle third in the new order. :param seq: Requested sequence to be rotated """ length = len(seq) length_of_thirds = length // 3 return seq[2*length_of_thirds:] + seq[:length_of_thirds] + seq[length_of_thirds:2*length_of_thirds] a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) a_longer_tuple = range(20) assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2) assert exchange_first_last(a_longer_tuple) == [19, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 0] assert remove_every_other(a_longer_tuple) == [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] assert remove_every_other(a_string) == 'ti sasrn' assert remove_four_leading_ending_every_other(a_longer_tuple) == [4, 6, 8, 10, 12, 14] assert remove_four_leading_ending_every_other(a_string) == ' sas' assert reverse_elements(a_longer_tuple) == [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] assert reverse_elements(a_string) == 'gnirts a si siht' assert rotate_thirds(a_longer_tuple) == [12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] assert rotate_thirds(a_string) == 'stringthis is a ' print('all tests passed')
c5cd6c1e7aec35f549bacc299f97f63741e28af3
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mgummel/lesson01/count_evens.py
142
3.765625
4
def count_evens(nums): count_variable = 0 for element in nums: if element % 2 == 0: count_variable += 1 return count_variable
06f63a74a86fe81d9f34848ac9ebc83fc3508883
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/anthony_mckeever/lesson3/exercise_2/strformat_lab.py
11,445
4.28125
4
""" Programming In Python - Lesson 3 Exercise 2: StrFormat Lab Code Poet: Anthony McKeever Start Date: 07/29/2019 End Date: 07/30/2019 """ def format_sequence(seq): """ Return a string that contains the contents of a sequence. Each item will be formatted as following: seq[0] : Will be padded with up to 2 additional zeros. seq[1] : Will be formated to the second decimal place seq[2] : Will be formated in scientific notation to the second decimal. seq[3] : Will be formated in scientific notation to the second decimal. Example: Input: (2, 123.4567, 10000, 12345.67) Output: file_002 : 123.46, 1.00e+04, 1.23e+04 :seq: The sequence to format and recieve as string. """ return "file_{:03d} :\t{:.2f}, {:.2e}, {:.2e}".format(*seq) def format_sequence2(seq): """ Return a string that contains the contents of a sequence. Each item will be formatted as following: seq[0] : Will be padded with up to 2 additional zeros. seq[1] : Will be formated to the second decimal place seq[2] : Will be formated in scientific notation to the second decimal. seq[3] : Will be formated in scientific notation to the second decimal. Example: Input: (2, 123.4567, 10000, 12345.67) Output: file_002 : 123.46, 1.00e+04, 1.23e+04 :seq: The sequence to format and recieve as string. """ return f"file_{seq[0]:03d} :\t{seq[1]:.2f}, {seq[2]:.2e}, {seq[3]:.2e}" def format_numbers(seq): """ Return a plural sensitve string that tells you how many numbers there are and what they are. Example: Input A: (0,) Output A: The 1 number is: 0 Input B: (1, 2, 3) Output B: The 3 numbers are: 1, 2, 3 :seq: The sequence to format into the string. """ size = len(seq) plural = "numbers are" if size > 1 else "number is" return ("The {} {}: " + ", ".join(["{:d}"] * size)).format(size, plural, *seq) def format_five_integers(seq): """ Return a string with the 5 integer sequence formated into "seq[3] seq[4] seq[0] seq[1] seq[2]" Each integer is padded by at least 1 zero. :seq: The sequence to format into the string. """ return f"{seq[3]:02d} {seq[4]:02d} {seq[2]:02d} {seq[0]:02d} {seq[1]:02d}" def weigh_fruit(seq): """ Return a string that displays the weight of each fruit. The sequence should contain two fruits and two weights in the pattern: ["fruit_a", fruit_a_weight, "fruit_b", fruit_b_weight] :seq: The sequence to format into the string. """ fruit_a = seq[0] an_a = get_grammar(fruit_a[:1]) fruit_b = seq[2] an_b = get_grammar(fruit_b[:1]) return f"The weight of {an_a} {fruit_a} is {seq[1]:.1f} and the weight of {an_b} {fruit_b} is {seq[3]:.1f}" def weigh_fruit2(seq): """ Return a string shows the percent difference of the weight of two fruits. The sequence should contain two fruits and two weights in the pattern: ["fruit_a", fruit_a_weight, "fruit_b", fruit_b_weight] :seq: The sequence to format into the string. """ fruit_a = seq[0] fruit_b = seq[2] an_a = get_grammar(fruit_a[:1]) an_b = get_grammar(fruit_b[:1]) weight_diff = round(seq[1] / seq[3], 1) weight_max, weight_min = max(1, weight_diff), min(1, weight_diff) size = "larger" if abs(weight_diff) > 1 else "smaller" display_weight = int((weight_max - weight_min) * 100) return f"The weight of {an_a} {fruit_a.upper()} is {display_weight}% {size} than the weight of {an_b} {fruit_b.upper()}." def get_grammar(char): """ Return a string of "an" if char is a vowel, or "a" if char is a consonant. :char: The character to evaluate. """ return "an" if char in ["a", "e", "i", "o", "u"] else "a" def create_table(seq): """ Return a string representing a table of Spacecrafts including a header. Header: ["Company:", "Name:", "Edition:", "Age:", "Cost:"] :seq: The sequence to transform into a table. """ table = [] company_len, name_len, edition_len, age_len, cost_len = get_lengths(seq) sep_strings = [("-" * (company_len + 2)), ("-" * (name_len + 2)), ("-" * (edition_len + 2)), ("-" * (age_len + 2)), ("-" * (cost_len + 2))] sep_line = "|" + "+".join(sep_strings) + "|" for item in seq: cost = f"${item[4]:.02f}" table.append(f"| {item[0]:<{company_len}} | {item[1]:<{name_len}} | {item[2]:<{edition_len}} | {item[3]:>{age_len}} | {cost:>{cost_len}} |") table.append(sep_line) header = ["Company:", "Name:", "Edition:", "Age:", "Cost:"] table.insert(0, sep_line) table.insert(1, f"| {header[0]:<{company_len}} | {header[1]:<{name_len}} | {header[2]:<{edition_len}} | {header[3]:<{age_len}} | {header[4]:<{cost_len}} |") table.insert(2, sep_line) return "\n".join(table) def get_lengths(seq): """ Return the longest length (integer) of each item in a sequence of 5 item sequences. :seq: The sequence to get lengths from. """ company_len = 0 name_len = 0 edition_len = 0 age_len = 0 cost_len = 0 for item in seq: cost = f"${item[4]:.02f}" company_len = len(item[0]) if len(item[0]) > company_len else company_len name_len = len(item[1]) if len(item[1]) > name_len else name_len edition_len = len(item[2]) if len(item[2]) > edition_len else edition_len age_len = len(str(item[3])) if len(str(item[3])) > age_len else age_len cost_len = len(cost) if len(cost) > cost_len else cost_len return company_len, name_len, edition_len, age_len, cost_len def run_tests(): """ Perform assertions against all the methods. Some helpers do not have explicit tests as they are called by functions that are being tested and there for are tested. """ print("Validate format_sequence") assert format_sequence((2, 123.4567, 10000, 12345.67)) == "file_002 :\t123.46, 1.00e+04, 1.23e+04" assert format_sequence((-1, 567.8910, 2, 555555.55555)) == "file_-01 :\t567.89, 2.00e+00, 5.56e+05" assert format_sequence((44444, 1.000235, 3452345234.2333212, 8)) == "file_44444 :\t1.00, 3.45e+09, 8.00e+00" print("Validate format_sequence2") assert format_sequence2((2, 123.4567, 10000, 12345.67)) == "file_002 :\t123.46, 1.00e+04, 1.23e+04" assert format_sequence2((-1, 567.8910, 2, 555555.55555)) == "file_-01 :\t567.89, 2.00e+00, 5.56e+05" assert format_sequence2((44444, 1.000235, 3452345234.2333212, 8)) == "file_44444 :\t1.00, 3.45e+09, 8.00e+00" print("Validate format_numbers") assert format_numbers((0,)) == "The 1 number is: 0" assert format_numbers((0, -1, 32)) == "The 3 numbers are: 0, -1, 32" assert format_numbers((333, 22 - 34, 2*2)) == "The 3 numbers are: 333, -12, 4" print("Validate format_five_integers") assert format_five_integers((4, 5, 3, 1, 2)) == "01 02 03 04 05" assert format_five_integers((-56, 50, 0, 11, 3458039485)) == "11 3458039485 00 -56 50" assert format_five_integers((20*5, 0, 0, 0, 3)) == "00 03 00 100 00" print("Validate weigh_fruit") assert weigh_fruit(["orange", 1.3, "lemon", 1.1]) == "The weight of an orange is 1.3 and the weight of a lemon is 1.1" assert weigh_fruit(["tomato", 1.1, "apple", 1]) == "The weight of a tomato is 1.1 and the weight of an apple is 1.0" assert weigh_fruit(["anti-banana", -1.4, "star fruit", 1.5]) == "The weight of an anti-banana is -1.4 and the weight of a star fruit is 1.5" print("Validate weigh_fruit2") assert weigh_fruit2(["coconut", 4, "lime", .5]) == "The weight of a COCONUT is 700% larger than the weight of a LIME." assert weigh_fruit2(["anti-lime", -.5, "lime", .5]) == "The weight of an ANTI-LIME is 200% smaller than the weight of a LIME." assert weigh_fruit2(["watermelon", 5, "anti-tomato", -1.1]) == "The weight of a WATERMELON is 550% larger than the weight of an ANTI-TOMATO." print("Validate create_table") input_table, output_table = get_table_test_case() assert create_table(input_table) == output_table print("Tests passed!") def get_table_test_case(): """ Return the test case input and expected output for validating create_table """ input_table = [["Ekiya Glyde Company", "78 Glyde XL 2016", "Personal Edition", 0, 2500599.99], ["Ekiya Glyde Company", "86 Glyde XL 3092", "Temporal Edition", -201, 6359950999.99], ["NASA", "Saturn V", "", 186 , 6417000.00], ["Ekiya Glyde Company", "32 Glyde Gx 2020", "Andromeda Edition", 2000000, 65000.000], ["SpaceX", "Falcon", "Heavy", 1, 90000000.99], ["Ai-Astra", "SpaceCraft 37", "Astral Explorer", 12993, 3750000.00]] output_table = ("|---------------------+------------------+-------------------+---------+----------------|\n" "| Company: | Name: | Edition: | Age: | Cost: |\n" "|---------------------+------------------+-------------------+---------+----------------|\n" "| Ekiya Glyde Company | 78 Glyde XL 2016 | Personal Edition | 0 | $2500599.99 |\n" "|---------------------+------------------+-------------------+---------+----------------|\n" "| Ekiya Glyde Company | 86 Glyde XL 3092 | Temporal Edition | -201 | $6359950999.99 |\n" "|---------------------+------------------+-------------------+---------+----------------|\n" "| NASA | Saturn V | | 186 | $6417000.00 |\n" "|---------------------+------------------+-------------------+---------+----------------|\n" "| Ekiya Glyde Company | 32 Glyde Gx 2020 | Andromeda Edition | 2000000 | $65000.00 |\n" "|---------------------+------------------+-------------------+---------+----------------|\n" "| SpaceX | Falcon | Heavy | 1 | $90000000.99 |\n" "|---------------------+------------------+-------------------+---------+----------------|\n" "| Ai-Astra | SpaceCraft 37 | Astral Explorer | 12993 | $3750000.00 |\n" "|---------------------+------------------+-------------------+---------+----------------|") return input_table, output_table def print_tasks(): """ Print the output for each task in the exercise. """ print("\nTask 1:") print(format_sequence((2, 123.4567, 10000, 12345.67))) print("\nTask 2:") print(format_sequence2((2, 123.4567, 10000, 12345.67))) print("\nTask 3:") print(format_numbers((0,))) print(format_numbers((0, 1))) print(format_numbers((0, 1, 2))) print(format_numbers((0, 1, 2, 3))) print("\nTask 4:") print(format_five_integers((4, 30, 2017, 2, 27))) print("\nTask 5a:") print(weigh_fruit(['orange', 1.3, 'lemon', 1.1])) print("\nTask 5b:") print(weigh_fruit2(['lemon', 1.1, 'orange', 1.3])) # Ignore "output_table" here since we only need the input table. The "create_table" function will do the rest. input_table, __ = get_table_test_case() print("\nTask 6:") print(create_table(input_table)) if __name__ == "__main__": print("Running Tests...") run_tests() print("\nPrinting Exercises...") print_tasks()
d385be11e4209ddf75fd6aad6a051e0c886d200b
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/calvin_fannin/lesson04/katafourteen.py
2,195
3.953125
4
#!/usr/bin/env python3 import sys import os import random import string def build_trigrams(words): """ build up the trigrams dict from the list of words returns a dict with: keys: word pairs values: list of followers """ trigrams = {} for i in range(len(words)-2): pair = tuple(words[i:i + 2]) follower = words[i+2] trigrams.setdefault(pair, []).append(follower) return trigrams def in_data(in_file): # open file and return words mywords = " " with open(in_file, "r") as in_doc: for line in in_doc.readlines(): for word in line.split(): mywords += " " + word # remove special chars mywords = mywords.translate({ord(i): None for i in '-.:!@#$%^&*()_+-=,./<>?"'}) return mywords.lower().split() def generate_new_text(dict_of_trigrams): new_text = [] # pick a workd pair as starting point start_pair = random.choice(list(dict_of_trigrams.keys())) # append to the list new_text = (list(start_pair)) # lookup random next word using the pair new_value = random.choice(dict_of_trigrams[start_pair]) new_text.append(new_value) for x in range(300): next_pair = tuple(new_text[-2:]) if next_pair in dict_of_trigrams.keys(): new_text.append(list(next_pair)[0]) new_text.append(list(next_pair)[1]) next_value = random.choice(dict_of_trigrams[next_pair]) new_text.append(next_value) else: return " ".join(new_text) return " ".join(new_text) if __name__ == "__main__": # get the filename from the command line try: filename = sys.argv[1] except IndexError: print("You must pass in a filename") sys.exit(1) # check to see if file exists if os.path.isfile(filename): words = in_data(filename) trigrams = build_trigrams(words) new_story = generate_new_text(trigrams) print(new_story) else: print("You must pass in a valid filename") sys.exit(1)
d526c9b6894043043b1069120492a35ea443d20d
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Deniss_Semcovs/Lesson04/dict_lab.py
1,906
4.15625
4
#!/usr/bin/env python3 #Create a dictionary print("Dictionaries 1") dValues = { "name":"Cris", "city":"Seattle", "cake":"Chocolate" } print(dValues) #Delete the entry print("Deleting entery for 'city'") if "city" in dValues: del dValues["city"] print(dValues) #Add an entry print("Adding a new item") dValues.update({"fruit":"Mango"}) print(dValues) print("Display the dictionary keys") print(dValues.keys()) print("Display the dictionary values") print(dValues.values()) print("Is 'cake' a key?") print("cake" in dValues.keys()) print("is 'Mango' a value?") print("Mango" in dValues.values()) #Using the dictionary from item 1: Make a dictionary #using the same keys but with the number of ‘t’s in each value as the value print("Dictionaries 2") print("Changing values") dValues["name"]=0 dValues["fruit"]=2 dValues["cake"]=2 print(dValues) print("Create sets") #Create sets s2, s3 and s4 that contain numbers from zero through twenty, #divisible by 2, 3 and 4 print("s2:") s2 = set() for i in range(20): if i % 2 == 0: s2.update([i]) else: pass print(s2) print("s3") s3 = set() for i in range(20): if i % 3 == 0: s3.update([i]) else: pass print(s3) print("s4") s4 = set() for i in range(20): if i % 4 == 0: s4.update([i]) else: pass print(s4) #Display if s3 is a subset of s2 and if s4 is a subset of s2 print("Is s3 a subset of s2?") s3.issubset(s2) print("Is s4 subset of s2?") s4.issubset(s2) #Create a set with the letters in ‘Python’ and add ‘i’ to the set. print("Sets2") wPython = set() wPython = set({"p","y","t","h","o","n"}) print(wPython) wPython.add("i") print(wPython) #Create a frozenset with the letters in ‘marathon’. wMarathon = frozenset({"m","a","r","a","t","h","o","n"}) print(wMarathon) #Display the union and intersection of the two sets. print(wPython.intersection(wMarathon))
ec4b2731e8b0313c92982e103f90dd6add95c020
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/stan_slov7/lesson05/mailroom3.py
9,868
3.765625
4
#!/usr/bin/env python3 #+-----------------------------------------+ #| Mailroom Part 3 - Assign #4 of Lesson 5 | #+-----------------------------------------+ import sys, os.path donor_dict = {'Jeff Bridges' : [1309.45, 7492.32], 'Alice Summers' : [3178.67, 9823.00], 'Henry Cavill' : [9132.92, 7837.50], 'Evie Styles' : [4592.25, 2145.90, 7314.87], 'Harvey Dent' : [14503.70] } main_prompt = "\n".join(("Welcome to the Mailroom - Part 3.", "Please choose one of the following options:", "1 - Send a Thank You.", "2 - Create a Report", "3 - Write Emails to All", "4 - Quit Program", ">>> ")) current_dir = os.getcwd() # New helper function for when any text input to prompt may get inadvertantly interrupted # or cause the program to inadvertantly crash due to unexpected exit such as via keyboard shortcut (ctrl+D exit) def safe_input(prompt = ''): try: result = input(prompt+"\n") except (KeyboardInterrupt, EOFError): result = None return result def write_file(fname,text): # Catch File Open Exceptions try: file = open(fname,'w') except (OSError, IOError): print("File Open Error occured for: ",fname) # Catch File Write Exceptions try: file.write(text) file.close() print("Written to .txt file:",fname,"...\n") except (OSError, IOError): print("File Write Error occured for: ",fname) # Change this to accomodate try--except input checks def send_thank_you(): prompt_name = "\n".join(("Please enter the full name of a donor currently in the database.", "Otherwise, enter a new full name to add a new (donor, donations[]) entry in that name.", "(You may type 'list' to see all current donor names in database, or type 'q' to go back.)", ">>> ")) while True: # donor_name = input(prompt_name) donor_name = safe_input(prompt_name) if donor_name.lower() == 'list': view_donor_names() print() elif donor_name.lower() == 'q': return #If user wants to return to main prompt during sending thank you email elif donor_name: break else: continue new_donation = get_amount() add_donation(donor_name, new_donation) print(email_templates(donor_name, new_donation, 2)) # send to second layout fuction option for send-thank-yous # unchanged def view_donor_names(): print("The donor dict contains the following donor names:\n") for entry in donor_dict: print(entry) #Since with dict this default refers to the keys i.e. names def get_amount(): prompt_amount = "Please enter a $ amount for the associated donation: \n" + ">>> " while True: # new_amount = float(input(prompt_amount)) # but for now wait to convert to float in case option to go back 'q' typed in by user # encase testing for float conversion of new_amount in try--except block, # then if input value cannot be converted to float: ValueError will be raised try: new_amount = float(safe_input(prompt_amount)) except ValueError: print("Invalid input: Please enter a nonzero positive decimal number (that can be converted to a float).\n") continue # throw the loop for another round until something changes. else: if new_amount > 0: break # value finally > 0 and decimal exit the loop and return the amount else: print("Invalid input: Please enter a nonzero positive decimal number.\n") continue # try again # return value when finally acceptable positive decimal number input return new_amount # replaces functionality of check_name() function as a whole: def add_donation(d_name, n_donation): # will add donation to existing list if donor exists, and instantiate new donor entry with empty donations list # which at this point will then prompt for first donation anyways donor_dict.setdefault(d_name, []).append(n_donation) print(email_templates(d_name, n_donation, 1)) # Updated to use a list comprehension def create_report(): # use list comprehension to store contents of dict into a list of tuples structure which can then be sorted and displayed donor_history = [(donor_name.title(), sum(amounts), len(amounts), sum(amounts)/len(amounts)) for (donor_name, amounts) in donor_dict.items()] donor_history = sorted(donor_history, key=sort_key, reverse=True) # reverse=True param sorts by highest to lowest total ie. descending ordered totals # sorted and changed in place by 2nd item in the new list comprehension ie. the total donation amt hdrfmt = "| {:<25s}|{:^18s}|{:^15s}|{:^18s}|".format("Donor Name:", "Total Donated:", "# Donations:", "Donation Avg:") divider = "-"*len(hdrfmt) rowfmt = "| {d_name:<25s}|${d_total:^17.2f}|{d_count:^15d}|${d_avg:^17.2f}|".format # create formatting using .format print(divider) print(hdrfmt) print(divider) for d_entry in donor_history: print(rowfmt(d_name=d_entry[0], d_total=d_entry[1], d_count=d_entry[2], d_avg=d_entry[3])) print(divider, "\n") # updated for try--except error check blocks on Open and Write files def write_email_all(): # This process goes through a try--except check for both opening the file and writing to the file, # using the newly added write_file error check function written/defined at the start of the program. div = "===------------------------------------------------------------------------------===\n" print("Preparing to send emails to all current donors in the database...\n") for fname, amts in donor_dict.items(): letter = email_templates(fname, sum(amts), 3) print(div) print(letter) # writing to file print(div) filename = "_".join(fname.title().split()) + ".txt" write_file(filename, letter) # produces .txt file in the current working directory (where this script is presently located) print("Files written to Current Working Directory located at: ", current_dir, "\n") def email_templates(dname, damt, template_num): #function returns the appropriate template based on template_num where the layout_dict is passed to .format() layout_dict = {"donor_name" : dname.title(), "donation_amount" : damt, "new_pgph_indent" : '\t', "line_break" : '\n\n', "greeting" : "Have a positively wonderful day!", "signature_indent" : ' '*25, "sender_indent" : ' '*20, "sender_name" : "Your Friendly Neighborhood CEOs" } added_donation_template = "\n".join(("\n\tNew Donation Amount of: ${donation_amount:.2f} has been recorded in the donor database,", "under the associated Donor Name: {donor_name}. Thanks for contributing!{line_break}")).format(**layout_dict) email_individual_template = "\n".join(("Dear {donor_name},{line_break}", "{new_pgph_indent}Thank you for the generous donation of: ${donation_amount:.2f}!{line_break}", "You will forever hold a place in our hearts! {greeting}{line_break}", "{sender_indent}Sincerely,{line_break}", "{signature_indent} - {sender_name}{line_break}")).format(**layout_dict) email_all_template = "\n".join(("Dear {donor_name},{line_break}", "{new_pgph_indent}Thank you for your repeated historical donations totalling: ${donation_amount:.2f}!{line_break}", "Your long time generosity recognized you as a pillar of our community!{line_break}", "{greeting}{line_break}", "{sender_indent}Sincerely,{line_break}", "{signature_indent} - {sender_name}{line_break}")).format(**layout_dict) templates = {1 : added_donation_template, 2 : email_individual_template, 3 : email_all_template } return templates[template_num] def sort_key(hist_tup): return hist_tup[1] #sorted by total (historical) donation amount def quit_program(): print("Thank you, this program will now terminate.") sys.exit() def main(): os.chdir(current_dir) # To ensure files get written in current working directory while True: # insert try--except block around response input, in case input cannot be converted to an int: (ValueError) try: response = int(safe_input(main_prompt)) except ValueError: print("Not a valid integer value. (between 1 - 4 for valid menu selection)") continue # run the input loop till accepted response if response in main_menu_dict: main_menu_dict.get(response)() # fetches relevant value based on key selection which is a call to the associated feature function else: print("Please enter a valid menu selection (between 1 - 4).\n") continue main_menu_dict = {1 : send_thank_you, 2 : create_report, 3 : write_email_all, 4 : quit_program } if __name__ == "__main__": # block to guard against your code running automatically if this module is imported main()
e878fd49b17b152e93fd91f6cfc88178b97fbf29
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/will_chang/lesson03/slicing_lab.py
2,639
4.3125
4
def exchange_first_last(seq): """Returns a copy of the given sequence with the first and last values swapped.""" if(len(seq) == 1): #Prevents duplicates if sequence only has one value. seq_copy = seq[:] else: seq_copy = seq[-1:]+seq[1:-1]+seq[:1] return seq_copy def exchange_every_other(seq): """Returns a copy of the given sequence with every other item removed.""" seq_copy = seq[:0] for i in range(len(seq)): if i % 2 == 0: #Copy every other item of the original sequence into the new sequence. seq_copy += seq[i:i+1] return seq_copy def first_last_four(seq): """Returns a copy of the given sequence with the first and last four items removed. Every other item is then removed from the remaining sequence.""" first_last_seq = seq[4:-4] #Placeholder sequence to remove first and last four items return exchange_every_other(first_last_seq) def reverse_elements(seq): """Returns a copy of the given sequence with the elements reversed.""" seq_copy = seq[::-1] return seq_copy def middle_last_first(seq): """Returns a copy of the given sequence with the following new order: middle third, last third, first third.""" seq_copy = seq[len(seq)//3:] + seq[:len(seq)//3] return seq_copy # Test variables a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) a_list = [3, 7, 26, 5, 1, 13, 22, 75, 9] # This block of code is used to test the exchange_first_last(seq) function. assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2) assert exchange_first_last(a_list) == [9, 7, 26, 5, 1, 13, 22, 75, 3] # This block of code is used to test the exchange_every_other(seq) function. assert exchange_every_other(a_string) == "ti sasrn" assert exchange_every_other(a_tuple) == (2, 13, 5) assert exchange_every_other(a_list) == [3, 26, 1, 22, 9] # This block of code is used to test the first_last_four(seq) function. assert first_last_four(a_string) == " sas" assert first_last_four(a_tuple) == () assert first_last_four(a_list) == [1] # This block of code is used to test reverse_elements(seq) function. assert reverse_elements(a_string) == "gnirts a si siht" assert reverse_elements(a_tuple) == (32, 5, 12, 13, 54, 2) assert reverse_elements(a_list) == [9, 75, 22, 13, 1, 5, 26, 7, 3] # This block of code is used to test the middle_last_first(seq) function. assert middle_last_first(a_string) == "is a stringthis " assert middle_last_first(a_tuple) == (13, 12, 5, 32, 2, 54) assert middle_last_first(a_list) == [5, 1, 13, 22, 75, 9, 3, 7, 26]
8ef5de28cc8dd558168a02d1bac9c33727337527
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/jacob_daylong/Lesson 8/circle.py
1,187
4.09375
4
import math class Circle(object): def __init__(self, radius): self.radius = radius @property def area(self): return (self.radius ** 2) * math.pi @property def diameter(self): return self.radius * 2 @diameter.setter def diameter(self, diameter): self.radius = diameter / 2 def __str__(self): return "Circle with a radius of {0:.2f}".format(self.radius) def __repr__(self): return 'Circle({})'.format(self.radius) def __add__(self, other): return self.__class__(self.radius + other.radius) def __mul__(self, other): 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 class Sphere(Circle): @property def area(self): return 4 * math.pi * (self.radius ** 2) @property def volume(self): return (4/3) * math.pi * (self.radius ** 3) def __str__(self): return "Sphere with a radius of {0:.2f}".format(self.radius) def __repr__(self): return 'Sphere({})'.format(self.radius)
5fdd8e8217317417bb9e5494433ce7d7db8998d7
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Steven/lesson03/slicing.py
2,184
4.5
4
#! bin/user/env python3 ''' Write some functions that take a sequence as an argument, and return a copy of that sequence: * with the first and last items exchanged. * with every other item removed. * with the first 4 and the last 4 items removed, and then every other item in the remaining sequence. * with the elements reversed (just with slicing). * with the last third, then first third, then the middle third in the new order. NOTE: These should work with ANY sequence – but you can use strings to test, if you like. ''' my_string = "this is a string" my_tuple = (2, 54, 13, 12, 5, 32) # exchange first and last positions in a sequence def exchange_first_last(seq): return seq[-1:] + seq[1:-1] + seq[:1] # return every other item in a sequence def every_other(seq): return seq[::2] # remove the first 4 and last 4 of a sequence but return every other remaining in the sequence def remove_four_everyOther(seq): return seq[4:-4:2] # reverse the sequence def reversed(seq): return seq[::-1] # given a sequence, return the last third, then first third and middle third in the new order def new_order(seq): step = len(seq) // 3 # determine length of sequence in thirds last = seq[-step:] # last third of a sequence first = seq[:step] # first third of a sequence middle = seq[step:-step] # middle third of a sequence return last + first + middle if __name__ == "__main__": # test exchange function assert exchange_first_last(my_string) == "ghis is a strint" assert exchange_first_last(my_tuple) == (32, 54, 13, 12, 5, 2) # test every other function assert every_other(my_string) == "ti sasrn" assert every_other(my_tuple) == (2, 13, 5) # test remove and return every other funtion assert remove_four_everyOther(my_string) == " sas" assert remove_four_everyOther(my_tuple) == () # test reversing function assert reversed(my_string) == "gnirts a si siht" assert reversed(my_tuple) == (32, 5, 12, 13, 54, 2) # test new order sequence function assert new_order(my_string) == "tringthis is a s" assert new_order(my_tuple) == (5, 32, 2, 54, 13, 12) print("tests passed")
65a1ee2bf6c0b2a1bf3217a82ab9450bef14e56f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/zach_meves/lesson08/test_circle.py
10,536
4.125
4
""" Test circle.py """ import unittest import os from circle import * import math class TestCircle(unittest.TestCase): """Tests the Circle class.""" def setUp(self) -> None: self.c1 = Circle(1) self.c2 = Circle(1.5) def test_init(self): """Test constructor.""" c = Circle(3) self.assertEqual(c.radius, 3) with self.assertRaises(TypeError): c = Circle() with self.assertRaises(TypeError): c = Circle(3, 2) def test_get_radius(self): self.assertEqual(self.c1.radius, 1) self.assertEqual(self.c2.radius, 1.5) def test_set_radius(self): self.c1.radius = 3.2 self.assertEqual(self.c1.radius, 3.2) self.assertEqual(self.c1.diameter, 6.4) self.c2.radius = 1 self.assertEqual(self.c2.radius, 1) self.assertEqual(self.c2.diameter, 2) with self.assertRaises(ValueError): self.c2.radius = -1 def test_get_diameter(self): self.assertEqual(self.c1.diameter, 2*self.c1.radius) self.assertEqual(self.c2.diameter, 2*self.c2.radius) def test_set_diameter(self): self.c1.diameter = .2 self.assertEqual(self.c1.radius, .1) self.assertEqual(self.c1.diameter, .2) self.c2.diameter = 0 self.assertEqual(self.c2.radius, 0) with self.assertRaises(ValueError): self.c1.diameter = -.2 def test_area(self): self.assertEqual(self.c1.area, math.pi * self.c1.radius ** 2) self.assertEqual(self.c2.area, math.pi * self.c2.radius ** 2) with self.assertRaises(AttributeError): self.c1.area = 3.2 def test_from_diameter(self): c = Circle.from_diameter(3) self.assertEqual(c.diameter, 3) self.assertEqual(c.radius, 1.5) with self.assertRaises(TypeError): c = Circle.from_diameter(3, 2) with self.assertRaises(TypeError): c = Circle.from_diameter() def test_repr(self): self.assertEqual(repr(self.c1), "Circle(1)") self.assertEqual(repr(self.c2), "Circle(1.5)") c1 = eval(repr(self.c1)) self.assertEqual(c1.radius, self.c1.radius) c2 = eval(repr(self.c2)) self.assertEqual(self.c2.radius, c2.radius) def test_str(self): self.assertEqual(str(self.c1), "Circle with radius: 1.000000") self.assertEqual(str(self.c2), "Circle with radius: 1.500000") def test_add_sub(self): c3 = self.c1 + self.c2 self.assertEqual(c3.radius, 2.5) self.assertEqual(self.c1.radius, 1) c4 = self.c2 - self.c1 self.assertEqual(c4.radius, .5) with self.assertRaises(ValueError): c5 = self.c1 - self.c2 with self.assertRaises(TypeError): c5 = self.c1 + 4 with self.assertRaises(TypeError): c5 = self.c1 - .2 self.assertEqual(self.c1 + self.c2, self.c2 + self.c1) def test_multiply_divide(self): c3 = 3 * self.c1 self.assertEqual(c3.radius, 3 * self.c1.radius) self.assertEqual(self.c1.radius, 1) c3 = self.c1 *43 self.assertEqual(c3.radius, 43 * self.c1.radius) c4 = self.c1 / 2 self.assertEqual(c4.radius, self.c1.radius / 2) with self.assertRaises(TypeError): x = 2 / self.c1 with self.assertRaises(TypeError): x = self.c1 * self.c2 with self.assertRaises(TypeError): x = self.c1 / self.c2 self.assertEqual(2 * self.c2, self.c2 * 2) def test_inplace(self): self.c1 += self.c2 self.assertEqual(self.c1.radius, 2.5) self.c2 *= 3 self.assertEqual(self.c2, Circle(1.5 * 3)) c = Circle(5.2) c -= Circle(2.2) self.assertEqual(c.radius, 3) c = Circle(8) c /= 2 self.assertEqual(c.radius, 4) def test_compare(self): self.assertTrue(self.c1 < self.c2) self.assertTrue(self.c1 <= self.c2) self.assertTrue(self.c1 <= Circle(1)) self.assertFalse(self.c2 < self.c1) self.assertFalse(self.c2 <= self.c1) self.assertTrue(self.c2 > self.c1) self.assertTrue(self.c2 >= self.c2) self.assertTrue(self.c2 >= Circle(1.5)) self.assertFalse(self.c1 > self.c2) self.assertFalse(self.c1 >= self.c2) self.assertTrue(self.c1 == Circle(1)) self.assertFalse(self.c1 == self.c2) self.assertTrue(self.c1 != self.c2) self.assertFalse(self.c1 != Circle(1)) def test_sort(self): lst = [0, 1, 5, 3, 9, 6, 2.2, 1.2] circles = [] for radius in lst: circles.append(Circle(radius)) circles.sort() self.assertEqual([c.radius for c in circles], sorted(lst)) def test_pow(self): self.assertEqual(self.c1 ** 1, self.c1) self.assertEqual(self.c1 ** 2, Circle(self.c1.radius ** 2)) self.assertEqual(self.c2 ** .2, Circle(self.c2.radius ** .2)) with self.assertRaises(TypeError): self.c1 ** self.c2 class TestSphere(unittest.TestCase): """Test the Sphere class.""" def setUp(self) -> None: self.c1 = Sphere(1) self.c2 = Sphere(1.5) def test_init(self): """Test constructor.""" c = Sphere(3) self.assertEqual(c.radius, 3) with self.assertRaises(TypeError): c = Sphere() with self.assertRaises(TypeError): c = Sphere(3, 2) def test_get_radius(self): self.assertEqual(self.c1.radius, 1) self.assertEqual(self.c2.radius, 1.5) def test_set_radius(self): self.c1.radius = 3.2 self.assertEqual(self.c1.radius, 3.2) self.assertEqual(self.c1.diameter, 6.4) self.c2.radius = 1 self.assertEqual(self.c2.radius, 1) self.assertEqual(self.c2.diameter, 2) with self.assertRaises(ValueError): self.c2.radius = -1 def test_get_diameter(self): self.assertEqual(self.c1.diameter, 2*self.c1.radius) self.assertEqual(self.c2.diameter, 2*self.c2.radius) def test_set_diameter(self): self.c1.diameter = .2 self.assertEqual(self.c1.radius, .1) self.assertEqual(self.c1.diameter, .2) self.c2.diameter = 0 self.assertEqual(self.c2.radius, 0) with self.assertRaises(ValueError): self.c1.diameter = -.2 def test_area(self): self.assertEqual(self.c1.area, 4 * math.pi * self.c1.radius ** 2) self.assertEqual(self.c2.area, 4 * math.pi * self.c2.radius ** 2) with self.assertRaises(AttributeError): self.c1.area = 3.2 def test_volume(self): self.assertEqual(self.c1.volume, 4/3 * math.pi * self.c1.radius ** 3) self.assertEqual(self.c2.volume, 4 / 3 * math.pi * self.c2.radius ** 3) with self.assertRaises(AttributeError): self.c1.volume = 3 def test_from_diameter(self): c = Sphere.from_diameter(3) self.assertEqual(c.diameter, 3) self.assertEqual(c.radius, 1.5) with self.assertRaises(TypeError): c = Sphere.from_diameter(3, 2) with self.assertRaises(TypeError): c = Sphere.from_diameter() def test_repr(self): self.assertEqual(repr(self.c1), "Sphere(1)") self.assertEqual(repr(self.c2), "Sphere(1.5)") c1 = eval(repr(self.c1)) self.assertEqual(c1.radius, self.c1.radius) c2 = eval(repr(self.c2)) self.assertEqual(self.c2.radius, c2.radius) def test_str(self): self.assertEqual(str(self.c1), "Sphere with radius: 1.000000") self.assertEqual(str(self.c2), "Sphere with radius: 1.500000") def test_add_sub(self): c3 = self.c1 + self.c2 self.assertEqual(c3.radius, 2.5) self.assertEqual(self.c1.radius, 1) c4 = self.c2 - self.c1 self.assertEqual(c4.radius, .5) with self.assertRaises(ValueError): c5 = self.c1 - self.c2 with self.assertRaises(TypeError): c5 = self.c1 + 4 with self.assertRaises(TypeError): c5 = self.c1 - .2 self.assertEqual(self.c1 + self.c2, self.c2 + self.c1) def test_multiply_divide(self): c3 = 3 * self.c1 self.assertEqual(c3.radius, 3 * self.c1.radius) self.assertEqual(self.c1.radius, 1) c3 = self.c1 *43 self.assertEqual(c3.radius, 43 * self.c1.radius) c4 = self.c1 / 2 self.assertEqual(c4.radius, self.c1.radius / 2) with self.assertRaises(TypeError): x = 2 / self.c1 with self.assertRaises(TypeError): x = self.c1 * self.c2 with self.assertRaises(TypeError): x = self.c1 / self.c2 self.assertEqual(2 * self.c2, self.c2 * 2) def test_inplace(self): self.c1 += self.c2 self.assertEqual(self.c1.radius, 2.5) self.c2 *= 3 self.assertEqual(self.c2, Sphere(1.5 * 3)) c = Sphere(5.2) c -= Sphere(2.2) self.assertEqual(c.radius, 3) c = Sphere(8) c /= 2 self.assertEqual(c.radius, 4) def test_compare(self): self.assertTrue(self.c1 < self.c2) self.assertTrue(self.c1 <= self.c2) self.assertTrue(self.c1 <= Sphere(1)) self.assertFalse(self.c2 < self.c1) self.assertFalse(self.c2 <= self.c1) self.assertTrue(self.c2 > self.c1) self.assertTrue(self.c2 >= self.c2) self.assertTrue(self.c2 >= Sphere(1.5)) self.assertFalse(self.c1 > self.c2) self.assertFalse(self.c1 >= self.c2) self.assertTrue(self.c1 == Sphere(1)) self.assertFalse(self.c1 == self.c2) self.assertTrue(self.c1 != self.c2) self.assertFalse(self.c1 != Sphere(1)) def test_sort(self): lst = [0, 1, 5, 3, 9, 6, 2.2, 1.2] spheres = [] for radius in lst: spheres.append(Sphere(radius)) spheres.sort() self.assertEqual([c.radius for c in spheres], sorted(lst)) def test_pow(self): self.assertEqual(self.c1 ** 1, self.c1) self.assertEqual(self.c1 ** 2, Sphere(self.c1.radius ** 2)) self.assertEqual(self.c2 ** .2, Sphere(self.c2.radius ** .2)) with self.assertRaises(TypeError): self.c1 ** self.c2 if __name__ == "__main__": os.chdir(os.path.dirname(__file__)) unittest.main()
3235b564b73ebaec5685d52174b8859e04d7b30a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/nick_miller/lesson01/codingbat-pushups/makes10.py
267
3.875
4
#!/usr/bin/env python def makes10(a, b): # if a == 10 or b == 10: # return True # if a + b == 10: # return True # else: # return False # # shortens to: return a == 10 or b == 10 or a + b == 10
2046b6e7f934c35cca4307316e6dcc0a36ad023a
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/grant_dowell/in_work/dict_lab.py
974
3.546875
4
#!/user/bin/env/ python3 """ Created on Thu Jan 23 18:21:24 2020 @author: Grant Dowell Dictionary and Set Lab """ dict_1 = {"name":"Chris", "city":"Seattle", "cake":"Chocolate"} print(dict_1) dict_1.pop("cake") print(dict_1) dict_1["fruit"] = "Mango" print(dict_1) print(dict_1.keys()) print(dict_1.values()) print("cake" in dict_1) print("fruit" in dict_1) print("Mango" in dict_1.values()) dict_2 = dict_1.copy() for key in dict_2: dict_2[key] = dict_1[key].lower().count('t') print(dict_2) # Sets def set_builder(max_val,div): s = set() for n in range(max_val): if n % div != 0: s.update([n]) return(s) s2 = set_builder(20,2) print(s2) s3 = set_builder(20,3) print(s3) s4 = set_builder(20,4) print(s4) print(s2.issubset(s3)) print(s2.issubset(s4)) # Sets 2 s_py = set('python') print(s_py) s_py.update('i') print(s_py) s_str2 = frozenset('marathon') print(s_str2) print(s_str2.intersection(s_py)) print(s_str2.union(s_py))
bc451f5e451696d92d005cf465993681ed70f4ae
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/tim_lurvey/lesson02/2.4_series.py
2,205
4.34375
4
#!/usr/bin/env python __author__ = 'Timothy Lurvey' import sys def sum_series(n, primer=(0, 1)): """This function returns the nth values in an lucas sequence where n is sum of the two previous terms. :param n: nth value to be returned from the sequence :type n: int :param primer: the first 2 integers of the sequence to be returned. (optional), default=(0,1) :type primer: sequence :returns: the nth position in the sequence :rtype: int""" # # test variable # try: assert (isinstance(n, int)) assert (n >= 0) except AssertionError: raise TypeError("n type must be a positive integer") from None # try: assert (all([isinstance(x, int) for x in primer])) except AssertionError: raise TypeError("primer must be a sequence of integers") from None # # working function # if n < 2: return primer[n] else: return sum_series(n=(n - 2), primer=primer) + sum_series(n=(n - 1), primer=primer) def fibonacci(n): """fibonacci(n) -> return the nth value in a fibonacci sequence""" return sum_series(n=n, primer=(0, 1)) def lucas(n): """lucas(n) -> return the nth value in a lucas sequence""" return sum_series(n=n, primer=(2, 1)) def tests(): nFibonacci = (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55) for i in range(len(nFibonacci)): assert (fibonacci(i) == nFibonacci[i]) print("Fibonacci test passed") # nLucas = [2, 1, 3, 4, 7, 11, 18, 29] for i in range(len(nLucas)): assert (lucas(i) == nLucas[i]) print("Lucas test passed") # primerCustom = (4, 3) nCustom = [4, 3, 7, 10, 17, 27, 44] for i in range(len(nCustom)): assert (sum_series(i, primer=primerCustom) == nCustom[i]) print("Custom (4,3) test passed") # # sum_series(3, primer="a") #fail # sum_series(3, primer=("a")) #fail # sum_series(-12) #fail # sum_series("a") #fail return True def main(args): tests() if __name__ == '__main__': main(sys.argv[1:])
ffcb1580b89f4c833ed2fda7c8628534b7724c6b
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/bplanica/codingbat.py
3,424
3.828125
4
# ------------------------- # # Breeanna Planica # Cosingbat.com exercises for Lesson 1 - Python 210 # Warmup-1 and Warmup-2 exercises # # https://codingbat.com/python # ------------------------- # # Warmup-1 > sleep_in def sleep_in(weekday, vacation): if not weekday or vacation: return True else: return False # Warmup-1 > monkey_trouble def monkey_trouble(a_smile, b_smile): if (a_smile and b_smile) or (not a_smile and not b_smile): return True else: return False # Warmup-1 > sum_double def sum_double(a, b): sum = a + b if a ==b: sum = sum * 2 return sum def sum_double(a, b): if a == b: sum = (2*(a+b)) return sum else: sum = a+b return sum # Warmup-1 > diff21 def diff21(n): if n >= 21: return (n - 21) * 2 elif n < 21: return 21 - n # Warmup-1 > parrot_trouble def parrot_trouble(talking, hour): if talking and (hour < 7 or hour > 20): return True else: return False # Warmup-1 > makes10 def makes10(a, b): if (a + b) == 10 or a == 10 or b == 10: return True else: return False # Warmup-1 > near_hundred def near_hundred(n): if abs(100 - n) <= 10 or abs(200 - n) <= 10: return True else: return False # Warmup-1 > pos_neg def pos_neg(a, b, negative): if negative and (a < 0 and b < 0): return True elif not negative and ((a < 0 and b >= 0) or (a >= 0 and b < 0)): return True else: return False # Warmup-1 > not_string def not_string(str): if str[:3] == "not": return str else: str = "not " + str return str # Warmup-1 > missing_char def missing_char(str, n): first = str[:n] second = str[n + 1:] return first + second # Warmup-1 > front_back def front_back(str): if len(str) == 1: return str else: length = len(str) first = str[:1] middle = str[1: length - 1] last = str[length - 1:] return last + middle + first # Warmup-1 > front3 def front3(str): if len(str) < 3: return str + str + str else: str = str[:3] return str + str + str # Warmup-2 > string_times def string_times(str, n): str = (str * n) return str # Warmup-2 > front_times def front_times(str, n): if len(str) < 3: str = (str * n) return str else: str = (str[:3] * n) return str # Warmup-2 > string_bits def string_bits(str): value = "" for i in range(len(str)): if i % 2 == 0: value = value + str[i] return value # Warmup-2 > string_splosion def string_splosion(str): value = "" for i in range(len(str)): value = value + str[:i+1] return value # Warmup-2 > last2 def last2(str): value = str[len(str)-2:] j = 0 for i in range(len(str)-2): match = str[i:i+2] if match == value: j = j + 1 return j # Warmup-2 > array_count9 def array_count9(nums): j = 0 for i in nums: if i == 9: j = j + 1 return j # Warmup-2 > array_front9 def array_front9(nums): end = len(nums) if end > 4: end = 4 for i in range(end): if nums[i] == 9: return True return False # Warmup-2 > array123 def array123(nums): for i in range(len(nums)-2): if nums[i] == 1 and (nums[i + 1] == 2) and (nums[i + 2] == 3): return True return False # Warmup-2 > string_match def string_match(a, b): j = 0 shorter = min(len(a), len(b)) for i in range(shorter - 1): a_sub = a[i:i + 2] b_sub = b[i:i + 2] if a_sub == b_sub: j = j + 1 return j
3e99ca23f0cb352898de2c6d948857e7d19c4648
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/mitch334/lesson04/dict_lab.py
2,131
4.3125
4
"""Lesson 04 | Dictionary and Set Lab""" # Goal: Learn the basic ins and outs of Python dictionaries and sets. # # When the script is run, it should accomplish the following four series of actions: #!/usr/bin/env python3 # Dictionaries 1 # Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate” (so the keys should be: “name”, etc, and values: “Chris”, etc.) # Display the dictionary. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} print(d) # Delete the entry for “cake”. # Display the dictionary. d.pop('cake') print(d) # Add an entry for “fruit” with “Mango” and display the dictionary. d['fruit'] = 'Mango' print(d) # Display the dictionary keys. # for key in d: # print(key) print(d.keys()) # Display the dictionary values. # for value in d.values(): # print(value) print(d.values()) # Display whether or not “cake” is a key in the dictionary (i.e. False) (now). print('cake' in d) # Display whether or not “Mango” is a value in the dictionary (i.e. True). # print(d.get('Mango')) print('Mango' in d.values()) # Dictionaries 2 # Using the dictionary from item 1: Make a dictionary using the same keys but with the number of ‘t’s in each value as the value (consider upper and lower case?). print('d: ',d) d2 = {} for k, v in d.items(): d2[k] = v.lower().count('t') print(d2) # Sets # Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible by 2, 3 and 4. # Display the sets. s2 = set(range(0, 21, 2)) print(s2) s3 = set(range(0, 21, 3)) print(s3) s4 = set(range(0, 21, 4)) print(s4) # Display if s3 is a subset of s2 (False) # and if s4 is a subset of s2 (True). print(s3.issubset(s2)) print(s4.issubset(s2)) # Sets 2 # Create a set with the letters in ‘Python’ and add ‘i’ to the set. s5 = set('Python') print(s5) s5.update('i') print(s5) # Create a frozenset with the letters in ‘marathon’. sf5 = frozenset('marathon') print(sf5) # display the union and intersection of the two sets. print(s5.union(sf5)) print(s5.intersection(sf5))
4120831e3897b34117d4b84f73ff8edb67254e40
DeadlyShanx/CTI110
/Celsius to Fahrenheit Table Python.py
246
3.640625
4
# Celsius to Fahrenheit Table # Date # CTI-110 P4HW2 - Celsius to Fahrenheit Table # Johnson # print('Celsius/Fahrenheit') for Celsius in range(21): fahrenheit=(9/5)*Celsius+32 print(Celsius,'=',format(fahrenheit,'.2f'))
fcbc5f5f1d5748360214967bcbbc42c01a7f0779
guipzaia/python-game
/campo.py
3,361
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Bibliotecas Padrão import random # Bibliotecas Personalizadas import printer import constantes as c from snake import Snake # Classe Campo (extends Printer) class Campo(printer.Printer): # Construtor da classe def __init__(self): # Atributos da classe self.data = { 'altura' : 30, # Altura do campo 'largura' : 50, # Largura do campo 'snake' : Snake(), # Snake 'seed' : None # Seed } # Espaçamento das colunas self.data['largura'] *= 2 # Método GET (mágico) # # Retorna o valor de um atributo específico da classe # # @param attr Nome do atributo # @return Valor do atributo # def __get__(self, attr): return self.data[attr] # Método SET (mágico) # # "Seta" um valor específico a um determinado atributo da classe # # @param attr Nome do atributo # @return val Valor do atributo # def __set__(self, attr, val): self.data[attr] = val # Método cria # # Cria o campo do jogo # def cria(self): self.criaSnake() # Cria a Snake self.criaSeed() # Cria Seed # Método criaSnake # # Cria a Snake no campo # def criaSnake(self): self.data['snake'].cria(self.data['altura'], self.data['largura']) # Método criaSeed # # Cria a "Seed" (para fazer a Snake crescer) # def criaSeed(self): while True: # Gera números randômicos para as coordenadas X e Y da Seed # dentro dos limites do campo x = random.randrange(2, (self.data['altura'] - 1), 1) y = random.randrange(3, (self.data['largura'] - 1), 2) # Flag para validar se a Seed foi criada corretamente valida = True # Percorre o "corpo" da Snake for corpo in self.data['snake'].data['corpo']: # Verifica se a Seed foi criada em um ponto onde a Snake já se econtra if corpo['x'] == x and corpo['y'] == y: valida = False break # Verifica se a Seed foi criada corretamente if valida: # "Seta" as coordenadas da Seed no campo self.data['seed'] = {'x': x, 'y': y} break # Método imprimeSeed # # Imprime a Seed no campo # def imprimeSeed(self): self.imprimeXY(self.data['seed']['x'], self.data['seed']['y'], c.C_x, c.AMARELO) # Método imprime # # Imprime o campo na tela # def imprime(self): # Imprime as partes superior e inferior do campo for i in xrange(1, self.data['largura'], 2): self.imprimeXY(1, i, c.C_x, c.VERDE) self.imprimeXY(self.data['altura'], i, c.C_x, c.VERDE) # Imprime as partes laterais do campo for i in xrange(2, self.data['altura'], 1): self.imprimeXY(i, 1, c.C_x, c.VERDE) self.imprimeXY(i, (self.data['largura'] - 1), c.C_x, c.VERDE) # Imprime a Snake no campo self.data['snake'].imprime() # Imprime a Seed no campo self.imprimeSeed() # Método moveSnake # # Movimenta a Snake pelo campo de acordo com a direção informada # # @param direc Direção informada # # @return integer 1: Movimento sem colisão e Snake cresceu # 0: Movimento sem colisão # -1: Colisão # def moveSnake(self, direc): # Movimenta a Snake ret = self.data['snake'].move(direc, self.data['seed'], self.data['altura'], self.data['largura']) # Verifica se Snake "comeu" a Seed if ret == 1: self.criaSeed() # Gera nova Seed self.imprimeSeed() # Imprime a Seed no campo return ret
7139d6e1cb237fcaa2fe0b432ba202af37d4a2c7
lucas-cavalcanti-ads/projetos-fiap
/1ANO/PYTHON/ListaExercicios/Lista02/ex04.py
225
3.84375
4
teclado = input("Digite o primeiro numero: ") num1 = int(teclado) teclado = input("Digite o segundo numero: ") num2 = int(teclado) potencia = num1 ** num2 potenciar = str(potencia) print("O resultado final e: " + potenciar)
f13effc92744a67522b672cc4bea0b23b1cb2ed6
lucas-cavalcanti-ads/projetos-fiap
/1ANO/PYTHON/ListaExercicios/Lista02/Ex08.py
263
3.78125
4
teclado = input("Digite o valor do prduto (R$): ") produto = float(teclado) teclado = input("Digite o valor do desconto (%): ") desconto = float(teclado) valorDesconto = produto - (produto * (desconto / 100)) print("O valor com desconto é: R$",valorDesconto,)
661f76129e30e8f780dd51f72b0e76e90477e7ba
lucas-cavalcanti-ads/projetos-fiap
/1ANO/PYTHON/ListaExercicios/Lista03/Ex10.py
402
3.796875
4
import math a = float(input("Digite o coeficiente a: ")) b = float(input("Digite o coeficiente b: ")) c = float(input("Digite o coeficiente c: ")) delta = ((b * b) - ((4 * a) * c)) if delta < 0: delta = delta * -1 rdelta = math.sqrt(delta) x1 = ((b * -1) + rdelta) / (2 * a) x2 = ((b * -1) - rdelta) / (2 * a) print("Coeficientes:a -",a,",b -",b,",c -",c) print("Resultados:x1- ",x1,", x2- ",x2)
99676f9a08690f1a09fecb838acafe1f8f6dd812
lucas-cavalcanti-ads/projetos-fiap
/1ANO/PYTHON/ListaExercicios/Lista02/Ex11.py
212
3.5625
4
teclado = input("Digite o seu RM(5 numeros): ") rm = int(teclado) num1 = rm % 10 num2 = num1 % 10 num3 = num2 % 10 num4 = num3 % 10 num5 = num4 % 10 resultado = num1 + num2 + num3 + num4 + num5 print(resultado)
5f212320614a24dbc1e59dcc0d46895778ac1307
lucas-cavalcanti-ads/projetos-fiap
/1ANO/PYTHON/ListaExercicios/Lista03/Ex11.py
1,136
3.90625
4
produto = float(input("Digite o valor da etiqueta do produto(R$): ")) tipoPagamento = int(input("Seleciona a forma de pagamento:1-Débito, 2-Crédito, 3-Cheque, 4-Dinheiro: ")) if tipoPagamento < 1 and tipoPagamento > 4: print("Forma de pagamento invalida") elif tipoPagamento == 1 or tipoPagamento == 3 or tipoPagamento == 4: valorFinal = produto - (produto * 0.1) print("Valor final do produto com desconto de 10%: R$",valorFinal) else: quantidade = int(input("Digite 1 para pagamento a vista no credito, 2 para parcelar em 2X, 4 para parcelar em 4X: ")) if quantidade == 1: valorFinal = produto - (produto * 0.05) print("Valor final do produto com desconto de 5%: R$",valorFinal) elif quantidade == 2: valorFinal = produto valorParcela = valorFinal / 2 print("Valor final do produto: R$",valorFinal," em 2X de R$",valorParcela) elif quantidade == 4: valorFinal = produto * 1.07 valorParcela = valorFinal / 4 print("Valor final do produto: R$",valorFinal," em 4X de R$",valorParcela) else: print("Valor de parcela invalido")
2bfc44ed603cc4ff70fef4e524918ef13944094d
lucas-cavalcanti-ads/projetos-fiap
/1ANO/PYTHON/ListaExercicios/Lista03/Ex13.py
600
4.125
4
from datetime import date print("Bem vindo ao programa de informacao de datas") hoje = date.today() print("Voce está executando esse programa em:",hoje.day,"/",hoje.month,"/",hoje.year) dia = int(input("Digite o dia de hoje(Ex:22, 09): ")) mes = int(input("Digite o mes de hoje(Ex:07, 12): ")) ano = int(input("Digite o ano de hoje(Ex:2016, 2020): ")) if mes == 2: if dia > 28 or dia < 1: print("Formato de data inválido") elif (dia > 31 or dia < 1) or (mes < 1 or mes > 12): print("Formato de data inválido") else: print("Data digitada:",dia,"/",mes,"/",ano)