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 |
|---|---|---|---|---|---|---|
0bee4d625f9278b438e51a96b23262f041e397fd | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jim_krecek/lesson08/circle.py | 1,274 | 3.796875 | 4 | import math
class Circle:
def __init__(self,rad):
self.rad = rad
@property
def diameter(self):
return self.rad*2
@diameter.setter
def diameter(self, dia):
self.rad = dia/2
@property
def area(self):
return math.pi*(self.rad**2)
@classmethod
def from_diameter(cls,diameter):
rad = diameter/2
return cls(rad)
def __str__(self):
return 'Circle with radius {0:.4f}'.format(self.rad)
def __repr__(self):
return 'Circle({})'.format(self.rad)
def __add__(self, other):
return self.__class__(self.rad + other.rad)
def __mul__(self, other):
return self.__class__(self.rad * other)
def __lt__(self, other):
return self.rad < other.rad
def __eq__(self, other):
return self.rad == other.rad
class Sphere(Circle):
def __str__(self):
return 'Sphere with radius {0:.4f}'.format(self.rad)
def __repr__(self):
return 'Sphere({})'.format(self.rad)
@property
def vol(self):
return math.pi * (1.333333) * (self.rad**3)
@property
def area(self):
return math.pi * 4 * (self.rad**2) |
06c598337b60c4930934d87ad490ea2c90506e4c | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/zhen_yang/lesson03/mailroom_part1.py | 5,913 | 3.5 | 4 | ######################
# Mail Room Part One #
######################
import sys
###############################################################################
# Data Sturcture for Mail Room
# 1. For the whole records are stored in a list so that we can keep adding now
# one to it.
# 2. For each record, we use tuple to make sure that a single record only can
# contain two items: "name" and "donation amount".
# 3. For 'donor name', we use string.
# 4. For 'donation amount', a list is used to donate more than once.
###############################################################################
donors_db = [('Adan William', [100.75, 1200, 3200.45]),
('Peter Chiykowski', [25.25, 4340.25]),
('Sara Gogo', [650]),
('Jason Zhang', [150.00, 35.50, 80.75]),
('Zooe Bezos', [10, 20])]
# prompt the three options for user
def ori_prompt():
print("Please choose from the following three options: ")
input_str = input("1.Send_ThankYouLetter 2.Create_Report 3.Quit : ")
input_str.strip() # remove whitespace
return input_str
##################
# prompt the user to input full name of the donor
##################
def fullname_prompt():
input_str = input("Please input donor's full name or input 'list' or input \
'quit' or 'q' to quit : ")
input_str.strip() # remove whitespace
if input_str.isdigit():
print("Input is a number not a name.")
return -1
elif input_str == 'quit' or input_str == 'q':
quit_program()
return input_str
##################
# prompt the user to input a donation amount
##################
def amount_prompt():
input_str = input("Please input the donation amount or input 'quit' \
or 'q' to quit : ")
input_str.strip()# remove whitespace
if input_str == 'quit':
quit_program()
try:
input_str = float(input_str)
except ValueError:
print("Please input a number for donation amount. Thank you!")
return -1
if float(input_str) >= 0:
input_amount = float(input_str)
return input_amount
else:
print("Plese input a positive number for donation amount. Thank you! ")
return -1
##################
# find the name from donors_db
##################
def found_name(my_name):
count = 0
for rowindex, row in enumerate(donors_db):
if row[0] == my_name:
return rowindex
return -1
##################
# add the amount to the existing donor on the donors_db
##################
def add_amount(amount, r_index):
donors_db[r_index][1].append(amount)
#print(f"3. Updated donor amount: {donors_db[r_index]}")
##################
# add the new orcorder to the donors_db
##################
def add_newrecord(d_name, amount):
# use tuple to make sure that a single record only can
# contain two items: "name" and "donation amount"
new_record = (d_name, [amount])
donors_db.append(new_record)
#print(f"1. Updated record {donors_db}")
##################
# print the thank you email
##################
def thankyou_letter(d_name, amount):
print(f"Dear {d_name}: ")
print(f" Thank you for your generous donation (${amount}) to us.")
print(" You have a wonderful day!")
#################################
# define send_thankyou() Option #
#################################
def send_thankyou(d_name):
while d_name == 'list':
print("The donor list: ")
for i in donors_db:
print(f"{i[0]} ", end="")
print("\n")
d_name = fullname_prompt()
if d_name == -1:
return
# for existing donor, add the donated amount to the list
row_index = found_name(d_name)
if row_index != -1:
amount = amount_prompt()
if amount != -1:
add_amount(amount, row_index)
# print thankyou_letter()
thankyou_letter(d_name, amount)
# for new donor,
# add the new donor name and donated amount to donors_db.
else:
amount = amount_prompt()
if amount != -1:
add_newrecord(d_name, amount)
# print thankyou_letter()
thankyou_letter(d_name, amount)
# sort key function
def sort_key(donor):
# sort the record based on the first name
return donor[0].split(" ")[0]
#################################
# define create_report() Option #
#################################
def create_report():
col_1 = 'Donor Name'
col_2 = 'Total Amount'
col_3 = 'Num Gifts'
col_4 = 'Average Amount'
formater_title = '{:^20s}|{:^15s}|{:^15s}|{:^20s}'
# scientific notation output
#formater_content = '{:<20s} ${:>14,.2e}{:>15d} ${:>17,.2e}'
formater_content = '{:<20s} ${:>14,.2f}{:>15d} ${:>17,.2f}'
# print the Title of the report
print(formater_title.format(col_1, col_2, col_3, col_4))
print('-' * 71)
# sort the record based on the first name
# the donors_db is a list not a dict.
for i in sorted(donors_db, key=sort_key):
print(formater_content.format(i[0], sum(i[1]),
len(i), sum(i[1]) / len(i)))
print("\n")
#################################
# define Quit_Program() Option #
#################################
def quit_program():
print("Bye!")
sys.exit()
#################################
# define main() function #
#################################
def main():
#Forever loop for letting user choose one of three options.
while True:
input_str = ori_prompt()
if input_str == '1':
d_name = fullname_prompt()
if d_name != -1:
send_thankyou(d_name)
elif input_str == '2':
create_report()
elif input_str == '3':
quit_program()
else:
print("Please input a vaild option.")
# put main interaction into the __main__ block
if __name__ == '__main__':
#calling the main() fuction
main()
|
db0ee3cb025c64d6654e3769f5f9b06c106e7928 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/luftsmeerflier/lesson03/list_lab.py | 1,445 | 4.09375 | 4 | #/usr/bin/env python3
def series_1():
fruits = ["Apples", "Pears", "Oranges", "Peaches"]
print(fruits)
response = input("Please add another fruit to the list\n")
fruits.append(response)
number = int(input("Please type a number (1-4)\n"))
print(number)
print(fruits[number-1])
fruits = ["Strawberry"] + fruits
print(fruits)
fruits.insert(0, "Banana")
print(fruits)
for fruit in fruits:
if fruit[0].lower() == 'p':
print(fruit)
return fruits
def series_2(fruits):
print("In series 2")
input_ = fruits
def list_gen(fruits):
print(fruits)
response = input("Type a fruit to delete\n").title()
if response not in fruits:
print("Try one of these:")
return list_gen(fruits[:] + fruits[:])
return [fruit for fruit in fruits if fruit != response]
print(fruits)
fruits.pop()
print(fruits)
print(list_gen(fruits))
def series_3(fruits):
def get_response():
response = input("Do you like {}? Y/N\n".format(fruit))
if not (response.upper() == 'Y' or response.upper() == 'N'):
print("Input Y or N")
return get_response()
elif response.upper() == 'N':
fruits.remove(fruit)
for fruit in fruits[:]:
get_response()
print(fruits)
def series_4(fruits):
print("In series 4")
reversed = [fruit[::-1] for fruit in fruits[:]]
fruits.pop()
print(reversed)
print(fruits)
def main():
list = series_1()
#series_2(list)
#series_3(list)
series_4(list)
if __name__ == "__main__":
main() |
3a356e02ce9627787acad99844395430500ad159 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/scott_bromley/lesson08/sparse_array_2D.py | 1,931 | 3.5625 | 4 | #!/usr/bin/env python3
import operator
class SparseArray2D(object):
"""
2D sparse array
"""
def __init__(self, sequence):
self.items = list(sequence)
self.sparse_array = dict(enumerate([[item for item in sublist if item != 0] for sublist in self.items]))
def __len__(self):
return sum([len(item) for item in self.items])
def __getitem__(self, key):
if isinstance(key, slice):
print(f"It's a single slice:{key}")
elif isinstance(key, tuple):
print(f"It's a multi-dimensional slice:{key}")
else:
try:
index = operator.index(key)
print(f"It's an index:{index}")
except TypeError:
raise
print("It's a simple index")
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
def __iter__(self):
pass
def __reversed__(self):
pass
def __contains__(self, item):
if isinstance(item, list):
return item in self.items
elif isinstance(item, int):
return any(item in sublist for sublist in self.items)
else:
try:
def __index__(self):
pass
def __str__(self):
f_string = "[{}]".format(", ".join(["{:3}"] * len(self.items[0])))
return "[{}]".format("\n ".join([f_string.format(*row) for row in self.items]))
def __repr__(self):
return f"SparseArray2D({self.items})"
def append(self, item):
pass
if __name__ == "__main__":
sa2d = SparseArray2D([[1, 0, 0, 0, 0, 0, 1, 0, 2],
[4, 5, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 6, 7, 8, 9]])
print(sa2d)
print(sa2d.__repr__())
sa2d.append([0, 0, 0, 0, 0, 0, 0, 0, 7])
print(sa2d.__contains__([1, 0, 0, 0, 0, 0, 1, 0, 2]))
print(sa2d.__contains__(6))
|
7b524f6f3e4d34af6e2d788d6326cc2cb5e087c4 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Nick_Lenssen/lesson08/circle.py | 1,758 | 3.96875 | 4 | #!/usr/bin/env python3
import math
class Circle:
def __init__(self, rad_length):
self.radius = rad_length
@property
def diameter(self):
return self.radius * 2
@diameter.setter
def diameter(self, x):
self.radius = x / 2
@property
def area(self):
return round(math.pi * self.radius**2,5)
@classmethod
def from_diameter(cls, diam):
radius = diam / 2
return cls(radius)
def __str__(self):
return "Circle with radius: {:.4f}".format(self.radius)
def __repr__(self):
return 'Circle({})'.format(self.radius)
def __add__(self, other):
return Circle(self.radius + other.radius)
def __iadd__(self, other):
return Circle(self.radius + other.radius)
def __sub__(self, other):
if self.radius - other.radius <= 0:
return Circle(0)
else:
return Circle(self.radius - other.radius)
def __mul__(self, other):
return Circle(self.radius * other)
def __imul__(self, other):
return Circle(self.radius * other)
def __rmul__(self, other):
return Circle(self.radius * other)
def __eq__(self, other):
return (self.radius == other.radius)
def __lt__(self, other):
return (self.radius < other.radius)
def sort_key(self):
return self.radius
class Sphere(Circle):
@property
def area(self):
return round(4*math.pi * self.radius**2,5)
@property
def volume(self):
return round(4/3*math.pi * self.radius**3,5)
def __str__(self):
return "Sphere with radius: {:.4f}".format(self.radius)
def __repr__(self):
return 'Sphere({})'.format(self.radius)
|
a9501b6b104327c93bc133367a8f499a41ec05fc | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jerickson/Lesson2/Ex2_3/fizzbuzz.py | 254 | 3.515625 | 4 | for i in range(1, 101):
s = ""
s = s + "fizz" if not i % 3 else s
s = s + "buzz" if not i % 5 else s
s = (
str(i) if not len(s) else s
) # If length is zero (not divisible by 3or5), print the number instead
print(f"{s}")
|
a54ad92e02225a6c676a658e28f4fa85ba1c55dd | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/daniel_gordon/lesson04/trigram.py | 3,150 | 3.96875 | 4 | import random
import sys
DEBUG = False
#Notes on cleaning text:
#Punctuation informs grammer,
#leaving in capitalization, commas, and periods helps keep sentance structure
#to allow more randomness, i'm going to seperate commas and periods into their own words for the trigram and rejoin them at the end
#parentheses and quotes come in pairs, I don't want to deal with that so I'm going to remove them entirely
remove = str.maketrans("","",'(){}[]"'+"'")
add_space = str.maketrans({',' : ' ,', '.' : ' .'})
def is_punctuation(string):
"""detects if a string is punctuation"""
return len(string) <= 1 and not string.isalnum()
def read_data(filename = "", header = True):
"""Processes data from a text file and returns a list of all words it contains
header : True if there is a header that needs skipping"""
if filename == "":
return "I wish I may I wish I might".split()
with open(filename) as file:
text = []
for line in file:
if header:
#Find START OF PROJECT line, otherwise do nothing
#I'm choosing to not hold myself responsible for the Table of Contents or similar
if line.startswith('***'):
header = False
else:
line = line.translate(remove)
line = line.translate(add_space)
text.extend(line.split())
if DEBUG: print(text)
#if header is still True, no text has been captured. Try again
if header: text = read_data(filename, False)
return text
def build_trigrams(words):
"""Builds a trigram from a list of words"""
"""Trigram is a dictionary of lists, using a word pair tuple as a key"""
trigram = {}
for i in range(len(words)-2):
trigram.setdefault((words[i], words[i+1]), []).append(words[i+2])
if DEBUG: print(trigram)
return trigram
def generate_text(trigram):
#Insure first key is capitalized, hope it's the begining of a sentance
key = "a"
while not key[0].istitle():
key = random.choice(list(trigram))
if is_punctuation(key[1]):
new_text = [key[0] + key[1]]
else:
new_text = list(key)
if DEBUG: print(f"starting key: {key}")
#generate text
for i in range(400):
next_word = random.choice(trigram[key])
key = (key[1], next_word)
#rejoin punctuation into the text
if is_punctuation(next_word):
new_text[-1] = new_text[-1] + next_word
else:
new_text.append(next_word)
#if the key is not in the trigram, it apears at the end of the sample
#most likely it is the natural place to end the text
if key not in trigram: break
return new_text
if __name__ == "__main__":
#get the filename from the command line, allow for default condition
try:
filename = sys.argv[1]
except IndexError:
filename = ""
#build the trigram
if DEBUG: print(f"filename: {filename}")
words = read_data(filename)
trigram = build_trigrams(words)
new_text = generate_text(trigram)
print(" ".join(new_text)) |
ad66a6638692e2db39b565bdd0d495e0663263e5 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/alexander_boone/lesson02/series.py | 2,193 | 4.21875 | 4 | def fibonacci(n):
"""Return nth integer in the Fibonacci series starting from index 0."""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def lucas(n):
"""Return nth integer in the Lucas series starting from index 0."""
if n == 0:
return 2
elif n == 1:
return 1
else:
return lucas(n - 1) + lucas(n - 2)
def sum_series(n, first_value = 0, second_value = 1):
"""
Return nth integer in a custom series starting from index 0 and parameters for the first and second series values.
Arguments:
first_value = 0; value at index n=0 of series
second_value = 1; value at index n=1 of series
This function provides a generalized version of the Fibonacci and Lucas integer series by allowing the user to
input the first two numbers of the series.
The default values of the first and second values of the series are 0 and 1, respectively, which are the first
two values of the Fibonacci series.
"""
if n == 0:
return first_value
elif n == 1:
return second_value
else:
return sum_series(n - 1, first_value, second_value) + sum_series(n - 2, first_value, second_value)
if __name__ == "__main__":
# run tests on fibonacci and lucas functions
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# run tests on sum_series function for arbirtary value inputs
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("tests passed") |
13ec5ffc09065c5fb91e5a6b478d9c06fddaf13e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jason_jenkins/lesson01/Warmup1.py | 1,439 | 3.6875 | 4 | # Lesson 1: Warmup Puzzles
def sleep_in(weekday, vacation):
if not weekday or vacation:
return True
else:
return False
def monkey_trouble(a_smile, b_smile):
return a_smile == b_smile
def sum_double(a, b):
if (a == b):
return (a+b) * 2
else:
return a+b
def diff21(n):
if(n > 21):
return abs(21 - n) * 2
else:
return abs(21 - n)
def parrot_trouble(talking, hour):
if (talking and (hour < 7 or hour > 20)):
return True
else:
return False
def makes10(a, b):
if a == 10 or b == 10:
return True
elif (a + b == 10):
return True
else:
return False
def near_hundred(n):
if(abs(n-100) <= 10 or abs(n-200) <= 10):
return True
else:
return False
def pos_neg(a , b, negative):
if(negative):
return (a < 0 and b < 0)
else:
return (a * b < 0)
def not_string(str):
if(str[0:3] == "not"):
return str
else:
return "not " + str
def missing_char(str, n):
str = str[0:n] + str[n+1:len(str)]
return str
def front_back(str):
if(len(str) <= 1):
return str
elif (len(str) == 2):
return str[1] + str[0]
else:
return str[len(str)-1] + str[1:len(str)-1] + str[0]
def front3(str):
if(str > 3):
str = str[0:3]
result = ""
for x in range(3):
result += str
return result
|
bd38ddfd901876fa796ad27e9043c79af75218f7 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/CCSt130/lesson03/list_lab_ex3-2.py | 11,393 | 4.34375 | 4 | # -*- coding: utf-8 -*-
""" This code will allow the user to append, insert or delete list contents. """
"""
Lesson03
Exercise 3.2 :: List Lab
Parts 1-4
Please note:
Some requirements were 'combined' by this student, and requirements may not be \
presented following the order in the assignment. Should that be a problem, \
please let me know.
@author: Chuck Stevens :: CCSt130
Created on Thu May 30 10:17:02 2019
"""
import sys
def list_printer(our_list):
""" This generic function will print any list with index. """
print()
print("Here's our current list: ")
for item in our_list:
print()
# Find index in list
position = our_list.index(item)
# Start at '1' rather than '0'
position += 1
# Print items with desired formatting
print("{}".format(position), end = ". ")
print(item)
def list_checker(item_list, find_char):
""" Generic function that finds items in list beginning with 'X'. """
# List to hold items found with search char
temp_list = []
for item in item_list:
if item.startswith(find_char):
# print(item)
# Add found items to a list
temp_list.append(item)
print()
print("Printing a list of all items containing '{}'.".format(find_char))
# Call print function
list_printer(temp_list)
def choose_sequence():
""" Take input to display and return 1 of 3 choices. """
input_msg = "Please enter 'A' to Append to the list, or 'I' to Insert: "
choice1 = 'A' # append
choice2 = 'I' # insert
choice3 = '+' # hidden option
choice1_msg = "You've chosen to Append to the list."
choice2_msg = "You've chosen to Insert at the beginning of the list."
choice3_msg = "Clearly, you are an insider."
while True:
# Note: change input to upper to make error handling easier
seq_choice = input(input_msg).title()
print()
print("You entered: '{}'.".format(seq_choice))
print()
# Note: Error handling could be more robust
if(seq_choice == choice1):
# print()
print(choice1_msg)
break
elif(seq_choice == choice2):
# print()
print(choice2_msg)
break
elif(seq_choice == choice3):
# print()
print(choice3_msg)
break
else:
print()
# print("Invalid Entry, please enter '{}' or '{}'.".format(choice1, choice2))
print("Invalid Entry--try again!")
return(seq_choice)
def copy_list(item_list):
# List to swap values of original list
temp_list = item_list[:]
# Empty list to append to
backward_list =[]
print()
print("We'll now print the list sdrawkcab, because that's the kind of crazy were are.")
for item in temp_list:
# Reverse letters in each item
item = item[::-1]
backward_list.append(item)
# Call function to print modified string
list_printer(backward_list)
# This could be its own separate function
# For readibility
# Find list length and assign value to a name
list_len = len(item_list)
# print("List length: ", end = "")
list_len-=1 # Offset index by 1
print()
print("We'll now delete the last element in the original list, for fun.")
# Remove the last element from original list
item_list.remove(item_list[list_len])
# Call function to print modified string
list_printer(item_list)
def do_you_like(sm_list):
""" Take input and delete if user doesn't like item. """
# This code is similar to choose_sequence and could probably be genericized
input_msg = "Please enter 'Y' if you Like an item, or 'N' to Delete it: "
choice1 = 'Y' # likes
choice2 = 'N' # Doesn't like, delete
choice1_msg = "Ok, we'll keep that in the list."
choice2_msg = "Ok, we'll delete that from the list."
# Temp list is required as the for loop will 'skip' an item...
# if the item before it is deleted. This must have something
# ...to do with indexing
# Empty swap list
temp_list = []
for element in sm_list:
print()
print("Do you like {}?".format(element))
# Note: change input to upper to make error handling easier
seq_choice = input(input_msg).title()
print()
print("You entered: '{}'.".format(seq_choice))
print()
# Note: Error handling could be more robust
if(seq_choice == choice1):
# print()
print(choice1_msg)
# Populate a new list to avoid skipping an element if 'No'
temp_list.append(element)
elif(seq_choice == choice2):
# print()
print(choice2_msg)
# Below will fail if n-1 has been deleted
# Remove element from list
# sm_list.remove(element)
else:
print()
print("Invalid Entry, please enter '{}' or '{}'.".format(choice1, choice2))
# print("Invalid Entry--try again!")
# Should the user delete the entire list
if not(temp_list):
print()
print("The list is empty!")
else:
list_printer(temp_list)
def fruity_list(sm_list):
""" This function asks for user input to modify list. """
# For fun and comparison purposes
big_fruit_list = ['Açaí','Apple','Akee','Apricot','Avocado','Banana','Bilberry','Blackberry',\
'Blackcurrant','Black sapote','Blueberry','Boysenberry','Buddhas hand',\
'Fingered citron','Crab apples','Currant','Cherry','Cherimoya','Custard Apple',\
'Chico fruit','Cloudberry','Coconut','Cranberry','Cucumber','Damson','Date',\
'Dragonfruit','Pitaya','Durian','Elderberry','Feijoa','Fig','Goji berry',\
'Gooseberry','Grape','Raisin','Grapefruit','Guava','Honeyberry','Huckleberry',\
'Jabuticaba','Jackfruit','Jambul','Japanese plum','Jostaberry','Jujube',\
'Juniper berry','Kiwano','Horned melon','Kiwifruit','Kumquat','Lemon','Lime',\
'Loquat','Longan','Lychee','Mango','Mangosteen','Marionberry','Melon','Cantaloupe',\
'Honeydew','Watermelon','Miracle fruit','Mulberry','Nectarine','Nance','Orange',\
'Blood orange','Clementine','Mandarine','Tangerine','Papaya','Passionfruit',\
'Peach','Pear','Persimmon','Plantain','Plum','Prune','Dried plum','Pineapple',\
'Pineberry','Plumcot','Pluot','Pomegranate','Pomelo','Purple mangosteen',\
'Quince','Raspberry','Salmonberry','Rambutan','Mamin Chino','Redcurrant',\
'Salal berry','Salak','Satsuma','Soursop','Star apple','Star fruit','Strawberry',\
'Surinam cherry','Tamarillo','Tamarind','Ugli fruit','White currant',\
'White sapote','Yuzu']
# Get user input regarding the list
# Please note: attempted try-except here but couldn't get it to operate as expected
while True:
# Print current items in list
print()
list_printer(sm_list)
# Ask user to type in name of favorite fruit
user_fav = input("Hey, what's your favorite fruit? Enter it please (e.g. 'Pear'): ")
# Change to title case for comparison with big_fruit_list
new_fruit = user_fav.title()
# Check if already in the list
if(new_fruit in sm_list):
print()
print("Your entry is already in our list! Good choice!")
break
# Check against Wikipedia exhaustive fruit list
# This is by no means 'error-proof', but imho a reasonable way of validating input
elif(new_fruit in big_fruit_list):
print()
print("Ok, we'll add '{}' to the list!".format(new_fruit))
# print()
# launch function to present and return choice
apnd_or_ins = choose_sequence()
if(apnd_or_ins == 'A'):
# Adding input to list
sm_list.append(new_fruit) # append to end of list
elif(apnd_or_ins == 'I'):
sm_list.insert(0, new_fruit) # insert at index 0 of list
elif(apnd_or_ins == '+'):
print()
print("This seems non-pythonic but we'll do it anyway.")
# Clunky, but...can't add str to list
temp_fruits = [new_fruit]
# Concatenate 2 lists
sm_list+=temp_fruits
# Minimal error handling...quit if invalid value passed.
else:
print()
print("Invalid input. Please rerun.")
sys.exit()
# Output revised list to screen
list_printer(sm_list)
break
else:
print()
print("Are you sure that's a fruit? Please check your spelling and try again.")
while True:
# Ask user for delete choice
# Doesn't cast input to int for str error handling
del_fruit = input("Please enter a number corresponding to the item you would like to delete: ")
# Ask user for delete choice and cast to int
# del_fruit = int(input("Please enter a number corresponding to the item you would like to delete: "))
print()
print("You entered '{}'".format(del_fruit), end = " :: ")
# Find list length
list_len = len(sm_list)
# Error handling of non-numeric entry
if(del_fruit.isalpha()):
print("Invalid entry--try again.")
else:
# Casting to int as input is str
del_fruit = int(del_fruit)
# Is user input out of range?
if((del_fruit < 1) or (del_fruit > list_len)):
print("Please enter a numeric value between 1 and {}.".format(list_len))
else: # Remove item based on valid input-1
del_fruit-=1 # Offset index by 1
# Print name of fruit
print("'{}' will be removed.".format(sm_list[del_fruit]))
# Remove item from list
sm_list.remove(sm_list[del_fruit])
# print()
list_printer(sm_list) # Call print function
break
if __name__ == "__main__":
def main():
search_char = "P" # Search_char could be a menu option
sm_fruit_list = ['Apple', 'Pear', 'Orange', 'Peach'] # removed plural
# Call function to modify list based on input
fruity_list(sm_fruit_list)
# Function iterates over list for 'X'
list_checker(sm_fruit_list, search_char)
# For test
# list_checker(big_fruit_list, search_char)
# Call function to reverse letters
copy_list(sm_fruit_list)
# Call function to determine user's likes or dislikes
do_you_like(sm_fruit_list)
print()
print("### End ###")
### Program entry point ###
main()
|
42f7b32603b36228ef572cce7685d4a8e68167a2 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/daniel_gordon/lesson02/grid_painter.py | 474 | 3.546875 | 4 | def PrintGrid(cells, size):
PrintLine(cells, size)
for i in range(cells):
PrintCell(cells, size)
PrintLine(cells, size)
return True
def PrintLine(cells, width):
for i in range(cells):
print('+', '-'*width, end = ' ')
print('+')
return True
def PrintCell(cells, size):
for i in range(size):
for i in range(cells):
print('|', ' '*size, end = ' ')
print('|')
return True
PrintGrid(10,1) |
f5229b31cae1ded118cf90a70af6c1531928a073 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/anthony_mckeever/lesson9/assignment_1/support.py | 10,582 | 4.0625 | 4 | """
Programming In Python - Lesson 9 Assignment 1: Object Oriented Mail Room
Code Poet: Anthony McKeever
Start Date: 09/10/2019
End Date: 09/15/2019
"""
import os
import os.path as path
import sys
import tempfile
class Helpers():
"""
A collection of helper functions used throughout the application.
All methods in this class are static and do not require you to instantiate
the Helpers as a new object.
"""
@staticmethod
def get_legnths(summaries, headers):
"""
Return the a collection of lenghts of the longest item between a summary and a header
:summaries: The donor summaries to compare
:headers: The headers of the table
"""
return [Helpers.get_length([x[0] for x in summaries], headers[0]),
Helpers.get_length([x[1] for x in summaries], headers[1]),
Helpers.get_length([x[2] for x in summaries], headers[2]),
Helpers.get_length([x[3] for x in summaries], headers[3])]
@staticmethod
def get_length(seq, name):
"""
Return the max length between the longest item in a sequence or the
name of the field.
:seq: The sequence to evaluate
:name: The name of the field to evaluate
"""
longest = sorted(seq, key=Helpers.length_key, reverse=True)[0]
return max(len(name), len(str(longest)))
@staticmethod
def length_key(item):
"""
The sort key for the length of items in a sequence
"""
return len(str(item))
@staticmethod
def get_table(header, summaries, report_name="Donor Summary Report"):
"""
Return a table as a string that reflects a donor summary report.
:header: A list of strings representing the table's header
"""
lengths = Helpers.get_legnths(summaries, header)
sep_strings = ["-" * (x + 2) for x in lengths]
sep_line = "|" + "+".join(sep_strings) + "|"
table = ["\n|" + "-" * (len(sep_line) - 2) + "|",
f"|{report_name:^{len(sep_line) - 2}}|",
sep_line,
Helpers.format_line(header, lengths),
sep_line]
table.extend([Helpers.format_line(d, lengths) + f"\n{sep_line}" for d in summaries])
return table
@staticmethod
def format_line(item, lengths):
"""
Return a formatted string that will fit in the donor summary table.
:item: The sequence of data to format.
:lengths: The lengths for each field of the table.
"""
return str(f"| {item[0]:<{lengths[0]}} | {item[1]:>{lengths[1]}} | "
f"{item[2]:>{lengths[2]}} | {item[3]:>{lengths[3]}} |")
@staticmethod
def safe_input(prompt):
"""
Return input from user or exit upon KeyboardInterupt or EOFError.
:prompt: What to ask the user for.
"""
output = None
try:
output = input(f"\n{prompt} > ")
except (KeyboardInterrupt, EOFError):
print("Exiting...")
sys.exit()
else:
return output
@staticmethod
def validate_donation(amount):
"""
Return a validated donation. Negative amounts or non-floatable values return 0.0
:amount: The donation amount to validate.
"""
try:
donation = float(amount)
except ValueError:
donation = 0.0
finally:
if donation <= 0.0:
print("Invalid amount. Try again.")
return donation
@staticmethod
def print_email(email):
"""
Print an email to the console.
:email: The email to print.
"""
print("\n\n----- PLEASE SEND THIS EMAIL TO THE DONOR -----\n\n")
print(email)
print("\n\n----- PLEASE SEND THIS EMAIL TO THE DONOR -----\n\n")
class FileHelpers():
"""
A collection of file helper methods for reading and writting files.
All methods in this class are static and do not require you to instantiate
a File_Helpers class.
"""
@staticmethod
def default_resource_file_path(file_name):
"""
Get the default resource file path relative to the script's location.
:file_name: The name of the resource file.
"""
default_resource_dir = path.dirname(path.realpath(__file__))
default_resource_dir = path.join(default_resource_dir, "resource")
return path.join(default_resource_dir, file_name)
@staticmethod
def open_file(file_path, output_type):
"""
Open a file and return its contents.
:file_path: The path of the file to read.
:output_type: The expected datatype of the output output.
"""
with open(file_path, "r") as in_file:
if output_type is type(str()):
return in_file.read()
else:
return in_file.readlines()
@staticmethod
def write_file(file_path, content, finish_msg=None):
"""
Write content to a file.
:file_path: The path of the file to read.
:content: The content to write.
:finish_msg: What to tell the user after the file is written
"""
with open(file_path, "w") as out_file:
if isinstance(content, list):
out_file.writelines(content)
else:
out_file.write(content)
if finish_msg is not None:
print(finish_msg)
@staticmethod
def get_user_output_path():
"""
Return the user's desired path for emails or None if the user leaves the choice blank.
Will prompt to create a directory if it does not exist.
"""
default_dir = tempfile.gettempdir()
print(f"\nDefault Directory: {default_dir}")
user_dir = Helpers.safe_input(str("Please enter a directory (Empty for Default,"
" \"Cancel\" to return to main menu)"))
user_dir = user_dir.lower()
if user_dir != "" and user_dir != "cancel":
if not os.path.exists(user_dir):
while True:
choice = Helpers.safe_input(str(f"The directory \"{user_dir}\" does not"
" exist. Do you want to create it?"
" ([Y]es / [N]o)"))
if choice.lower() in ["yes", "y"]:
os.makedirs(user_dir)
break
elif choice.lower() in ["no", "n"]:
print("Using default directory instead.")
user_dir = default_dir
break
print("Invalid choice. Please enter \"Yes\" or \"No\"")
elif user_dir != "cancel":
return default_dir
elif user_dir == "cancel":
return None
return user_dir
class MenuItem():
"""
A class representing an item in a menu prompt.
"""
def __init__(self, name, description, method, tabs=2):
"""
Initializes a menu item
:self: The Class.
:name: Name of the menu item (to be printed for the user)
:description: The description of the action this menu items represents.
:method: The function to execute when the menu item is called.
"""
self.name = name
self.description = description
self.method = method
self.total_tabs = tabs
def __str__(self):
"""
Get a string representing the menu item.
"""
tabs = "\t" * self.total_tabs
self_string = f"{self.name}{tabs}{self.description}"
return self.name if self.description is None else self_string
class MenuDriven():
"""
A class that represents a Menu Driven collection of actions.
Usage:
Instantiate the MenuDriven object as you would any object.
Ensure the :menu_items: parameter is a list of MenuItem objects.
To execute the menu, call run_menu().
Example:
menu_items = [MenuItem("My Option", "Does a thing", some_function)]
my_menu = MenuDriven("Some Text", menu_items, "Lets do a thing!", invalid=sys.exit)
my_menu.run_menu()
"""
def __init__(self, menu_text, menu_items, prompt_string, show_main=False, invalid=None):
"""
Initializes a Menu Driven object.
:self: The Class
:menu_text: The heading of the menu.
:menu_items: The collection of MenuItem objects to drive.
:prompt_string: What to ask the user
:show_main: Whether or not to show the user how to return to the main menu.
:invalid: What to do if a user inputs an invalid menu option
(Default = None, tell user their input is invalid and reprompt)
"""
self.menu_text = menu_text
self.prompt = prompt_string
self.menu_items = {str(i+1): m for i, m in enumerate(menu_items)}
self.invalid_option = invalid
if show_main:
main_entry = MenuItem("Return to Main Menu", None, None)
self.menu_items.update({str(len(self.menu_items)+1): main_entry})
exit_entry = MenuItem("Exit the Script", None, sys.exit)
self.menu_items.update({str(len(self.menu_items)+1): exit_entry})
def print_menu(self):
"""
Print the menu.
"""
print(f"\n{self.menu_text}")
for k, v in self.menu_items.items():
print( f"\t{k} - {str(v)}")
def run_menu(self):
"""
Executes the menu. Handles printing the menu and handling user response.
"""
self.print_menu()
while True:
user_choice = Helpers.safe_input(self.prompt)
choice = self.menu_items.get(user_choice)
if choice is not None:
if choice.method:
choice.method()
if choice.name != "List Donors":
break
else:
if self.invalid_option is None:
print("Invalid choice. Please select from the available options.")
else:
self.invalid_option(user_choice)
break
|
713775c79a03d7c700411131e7f5db82358fc3cd | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mitch334/lesson02/grid_printer.py | 1,796 | 4.53125 | 5 | # Lesson 02 : Grid Printer Exercise
# Write a function that draws a grid like the following:
#
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | |
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | |
# + - - - - + - - - - +
# Part 1: Print the simple grid
def print_grid_simple():
plus = '+ - - - - + - - - - +'
pipe = '| | |'
for i in range(2):
print(plus)
for i in range(4):
print(pipe)
print(plus)
# print_grid_simple()
# Part 2: Print the simple grid with a squre input size (n)
def print_grid(n):
grid_size = n//2 # Divide the size by two sections
if n & 1: # Used to set the correct spacing for odd/even n
pipe_space = n
else:
pipe_space = n + 1
# print(n,' | ',grid_size,' | ',pipe_space)
plus = '+' + ' -'*grid_size + ' +' + ' -'*grid_size + ' +'
pipe = '|' + ' '*pipe_space + '|' + ' '*pipe_space + '|'
for i in range(2):
print(plus)
for i in range(grid_size):
print(pipe)
print(plus)
# print_grid(10)
# Part 3: Write a function that draws a similar grid with a specified
# number of rows and columns, and with each cell a given size.
# Example: print_grid2(3,4)
# (three rows, three columns, and each grid cell four “units” in size)
def print_grid2(n,s):
grid_size = s
pipe_space = s*2 + 1
# print(s,' | ',grid_size,' | ',pipe_space)
plus = '+' + (' -'*grid_size + ' +')*n
pipe = '|' + (' '*pipe_space + '|')*n
for i in range(n):
print(plus)
for i in range(grid_size):
print(pipe)
print(plus)
# print_grid2(3,4)
# print_grid2(5,3)
|
be044b987806168080c2e40cdba91c25488b041b | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/eric_grandeo/lesson03/strformat_lab.py | 1,550 | 3.75 | 4 | #!/usr/bin/env python3
#Task One
s = "file_{:0>3d} : {:.2f}, {:.2e}, {:.2e}"
print(s.format( 2, 123.4567, 10000, 12345.67))
#Task Two
file = 2
num1 = 123.4567
num2 = 10000
num3 = 12345.67
print(f"file_{file:0>3d} : {num1:.2f}, {num2:.2e}, {num3:.2e}")
#Task Three
#"the 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3)
def formatter(in_tuple):
l = len(in_tuple)
form_string = "the {} numbers are: " + ",".join(["{}"]*l)
return form_string.format(l,*in_tuple)
print(formatter((2,3,5)))
print(formatter((2,3,5,7,9)))
#Task Four
def task_four(tup):
new_string = "{:0>2d}, {}, {}, {:0>2d}, {}"
return new_string.format(tup[3], tup[4], tup[2], tup[0], tup[1])
print(task_four((4, 30, 2017, 2, 27)))
#'02 27 2017 04 30'
#Task Five
test_list = ['oranges', 1.3, 'lemons', 1.1]
#The weight of an orange is 1.3 and the weight of a lemon is 1.1
print(f'''The weight of an {(test_list[0][:-1]).upper()} is {(test_list[1]) *1.2} and the weight of a {(test_list[2][:-1]).upper()} is {(test_list[3])*1.2}''')
#Task 6
def align_test(item):
print("{:^15} {:^10} {:^15}".format("Name", "Age", "Cost"))
for x in item:
print("{:^15} {:^10} {:^15}".format(*x))
align_test((('Eric', 45, '$100'), ('Vivie', 4, "$1,000"), ('Jack', 1,'$10,000'),('Christina', 42, '$10')))
#bonus: given a tuple with 10 consecutive numbers, can you work how to quickly print the tuple in columns
#that are 5 charaters wide? It can be done on one short line!
tup_ex = (1,2,3,4,5,6,7,8,9,10)
print(''.join([f"{i:^5}" for i in tup_ex]))
|
d6273747b57f69b222565ccfe94ee5dcfe1e271e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/nskvarch/Lesson2/grid_printer_part2.py | 492 | 4.15625 | 4 | #Part 2 of the grid printer exercise, created by Niels Skvarch
plus = '+'
minus = '-'
pipe = '|'
space = ' '
def print_grid(n):
print(plus, n * minus, plus, n * minus, plus)
for i in range(n):
print(pipe, n * space, pipe, n * space, pipe)
print(plus, n * minus, plus, n * minus, plus)
for i in range(n):
print(pipe, n * space, pipe, n * space, pipe)
print(plus, n * minus, plus, n * minus, plus)
x = int(input("What size grid would you like?: "))
print_grid(x)
|
a7974c7692bd8e6d9105879cb823a173b81a084d | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Isabella_Kemp/lesson02/series.py | 2,165 | 4.25 | 4 | #Isabella Kemp
#Jan-6-20
#Fibonacci Series
'''def fibonacci(n): #First attempt at this logic
fibSeries = [0,1,1]
if n==0:
return 0
if n == 1 or n == 2:
return 1
for x in range (3,n+1):
calc = fibSeries[x-2] + fibSeries[x-1]
fibSeries.append(calc)
print (fibSeries[:]) #prints the entire fib series
return fibSeries[-1] # returns the last value in the series
print (fibonacci(5))'''
#Fibonacci Series computed. Series starts with 0 and 1, the following integer is the
#summation of the previous two.
def fibonacci(n):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
#Lucas Numbers. Series starts with 2 at 0 index followed by 1.
def lucas(n):
#lucasSeries = [2,1]
if n == 0:
return 2
if n == 1:
return 1
return lucas(n-1) + lucas(n-2)
#sum series will return fibonacci sequence if no optional parameters are called
#b and c are optional parameters. If 2 and 1 are called for optional parameters
#lucas sequence is called. Other optional parameters gives a new series.
def sum_series(n,b=0,c=1):
if n == 0:
return b
if n == 1:
return c
return sum_series(n-1, b, c) + sum_series(n-2, b, c)
#Tests
if __name__ == "__main__":
# run some tests
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("tests passed")
|
f4590b1b6b19c724612ef669022344f4eed77cc1 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/tihsle/lesson02/series.py | 2,052 | 3.921875 | 4 | def fibonacci(n):
#Fibonacci sequence
#initialize variables
fib = []
nth = 0
for num in range(0,n+1):
if num == 0:
fib.append(0)
elif num == 1:
fib.append(1)
elif num > 1:
nth = fib[-2] + fib[-1]
fib.append(nth)
return(fib[n])
def lucas(n):
#Lucas Numbers
luc = []
nth = 0
for num in range(0,n+1):
if num == 0:
luc.append(2)
elif num == 1:
luc.append(1)
elif num > 1:
nth = luc[-2] + luc[-1]
luc.append(nth)
return(luc[n])
def sum_series(n, a=0, b=1):
#related number sequence series
seq = []
nth = 0
for num in range(0,n+1):
if num == 0:
seq.append(a)
elif num == 1:
seq.append(b)
elif num > 1:
nth = seq[-2] + seq[-1]
seq.append(nth)
return(seq[n])
# tests
print ("fibonacci(7) = " + str(fibonacci(7)))
print ("lucas(7) = " + str(lucas(7)))
print("sum series fib 7 = " + str(sum_series(7)))
print("sum series luc 7 = " + str(sum_series(7, 2, 1)))
# asserts test block
if __name__ == "__main__":
# run some tests
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("assert tests passed")
|
6f1d8ff7052769508a3b05fd4ed1e92f8a1c936e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/cjfortu/lesson04/dict_lab.py | 1,778 | 4 | 4 | #!/usr/bin/env python
"""
Dictionary and Set Lab
The starting dict is a global value.
Dictionaries1() and Dictionaries2() use the starting dict.
"""
start_dict = dict(name='Chris', city='Seattle', cake='Chocolate')
def dictionaries1(): # pretty straightforward
print(start_dict)
start_dict.pop('cake')
print(start_dict)
start_dict['fruit'] = 'Mango'
print(start_dict)
print(start_dict.keys())
print(start_dict.values())
print('cake' in start_dict)
print('Mango' in start_dict.values())
def dictionaries2():
count_t = [] # establish an empty list for future population with count values
for item in start_dict.values():
count_t.append(item.lower().count('t')) # number of 't' characters per string, case insensitive.
dict2 = dict(name=count_t[0], city=count_t[1], cake=count_t[2]) # create new dict
print(dict2)
def set1():
"""
Set1
This could have been done with 'if-elif-else' structure, but I used a dict switch to give \
it a try.
"""
# initialize empty sets
s2 = set([])
s3 = set([])
s4 = set([])
# define functions to update sets
def s_2():
s2.update([i])
def s_3():
s3.update([i])
def s_4():
s4.update([i])
switch_set_dict = {2: s_2, 3: s_3, 4: s_4}
for i in range(21):
for val in [2, 3, 4]:
# execute switch dict if divisible by 2, 3, or 4.
if i % val == 0:
switch_set_dict.get(val)()
print(s2, '\n', s3, '\n', s4)
print(s3.issubset(s2))
print(s4.issubset(s2))
def set2(): # pretty straightforward
P_set = set('Python')
P_set.update('i')
m_set = frozenset('marathon')
print(P_set.union(m_set))
print(P_set.intersection(m_set)) |
406615dc9650d9de78c48a1482be9b8a07936f37 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Shweta/lesson02/gridFunction.py | 617 | 4.03125 | 4 | #Print Grid Value using python function
def plusminus(m):
for i in range(2):
print('+',end=' ')
print(('-' + ' ' ) * int(m),end=' ')
print('+')
def pipe(m):
for i in range(m):
for i in range(3):
print('|',end=' ')
print(' ' * int(m),end=' ')
print()
def print_grid(n):
if n%2==0:
print("Please enter odd number to make the grid")
else:
m=(n-1)//2
plusminus(m)
for i in range(2):
pipe(m)
plusminus(m)
print_grid(15)
|
13b17c62ec287e6fbd23b8171dddd58f834334de | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/CCSt130/lesson02/series_part2.py | 4,041 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
This code will calculate either the Fibonacci Sequence or the Lucas Sequence
based the user's selection, to F_n.
"""
"""
Lesson02 :: Fibonacci Series Exercise
Part 2
Please note:
This version replaces redundant Fibonacci and Lucas functions with one 'sum_series' function
@author: Chuck Stevens :: CCSt130
Created on Tue May 21 10:38:35 2019
"""
import sys
def sum_series(seq, fn): # input: Sequence and F_n
# Generic sequence
if(seq == 'F' or seq == 'f'):
seed_sequence = [0, 1] # Fibonacci seed values
elif(seq == 'L' or seq == 'l'):
seed_sequence = [2, 1] # Lucas seed values
# Better error handling needed here
else:
print("Sequence choice invalid.")
print()
sys.exit()
calc_sequence = seed_sequence[:] # Used for calculating the sequence
sequence_list = seed_sequence[:] # List to hold sequence after calculating
swap_sequence = None # temp name a.k.a. swap variable
# Confirm expected values
print()
print("seed_sequence values:")
print(seed_sequence)
print()
print("Initial value of sequence (list): ")
print(sequence_list)
print()
i = 0 # counter for while loop
while(i <= (fn-2)): # n is offset by two as the seed values are index 0, 1
print("Printing calc_sequence index 0: ", end = '')
print(calc_sequence[0]) # Test
swap_sequence = calc_sequence[0] # first element in list to temp name
calc_sequence[0] = calc_sequence[1] # value of second element becomes the first
calc_sequence[1] = swap_sequence + calc_sequence[1] # sum index 0, 1 to get subsequent value
# calc_sequence[1] += swap_sequence # alternative expression
sequence_list.append(calc_sequence[1]) # append to list starting at sequence[2]
i+=1 # increment while loop
# In order to print the first 2 (seed) values, the last 2 are printed outside the loop
print("Printing calc_sequence index 0: ", end = '')
print(calc_sequence[0]) # Test
print("Printing calc_sequence index 0: ", end = '')
print(calc_sequence[1]) # Test
# Confirm expected values
print()
print("Ending calc_sequence values:")
print(calc_sequence)
print()
print("Sequence (list) is:")
print (sequence_list)
return(calc_sequence[1])
def choose_sequence(): # Take input to display either Fibonacci or Lucas
seq_choice = input("Please enter 'F' for the Fibonacci Sequence, or 'L' for the Lucas Sequence : ")
# Note: change input to upper to make error handling easier
print()
print("You entered: '%s'." % (seq_choice))
print()
if(seq_choice == 'F' or seq_choice == 'f'):
print("You've chosen to calculate the Fibonacci sequence!")
elif(seq_choice == 'L' or seq_choice == 'l'):
print("You've chosen to calculate the Lucas sequence!")
else:
print()
print("Invalid Entry, please rerun.")
# Note: Error handling needs to be more robust
sys.exit()
return(seq_choice)
def choose_Fn(): # Take input for F_n to determine end point of sequence
# Determine F_n, cast to int
n_choice = int(input("Please enter a value 'n' for the maximum results to be displayed: "))
print()
print("You entered: '%s'." % (n_choice))
if(n_choice >= 0):
return(n_choice)
else:
print()
print("Invalid Entry, please rerun.")
# Note: Error handling needs to be more robust
sys.exit
if __name__ == "__main__":
def main():
# initialize functions to determine which series to run and F_n
x = choose_sequence()
y = choose_Fn()
# calculate series
z = sum_series(x, y)
print()
print("The value for the 'Nth' position in the Sequence where 'N'=='%d' is: %d" % (y, z))
print()
main() |
17ff33d3d3f30f91fad231d74de4869231456302 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/anthony_mckeever/lesson8/assignment_1/sphere.py | 1,218 | 4.40625 | 4 | """
Programming In Python - Lesson 8 Assignment 1: Spheres
Code Poet: Anthony McKeever
Start Date: 09/06/2019
End Date: 09/06/2019
"""
import math
from circle import Circle
class Sphere(Circle):
"""
An object representing a Sphere.
"""
def __init__(self, radius):
"""
Initializes a Sphere object
:self: The class
:radius: The desired radius of the Sphere.
"""
super().__init__(radius)
@classmethod
def from_diameter(self, diameter):
"""
Instantiates a Sphere from a diameter value.
:self: The class
:diameter: The desired diameter of the Sphere.
"""
return super().from_diameter(diameter)
@property
def volume(self):
"""
Return the sphere's volume.
Formula: 4/3 * pi * r^3
"""
return (4 / 3) * math.pi * (self.radius ** 3)
@property
def area(self):
"""
Return the sphere's area
Formula: 4 * pi * r^2
"""
return 4 * math.pi * (self.radius ** 2)
def __str__(self):
return f"Sphere with radius: {self.radius}"
def __repr__(self):
return f"Sphere({self.radius})"
|
b70be8f91eac1bf85f95077c4b735d1e13f392fa | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/travis_nelson/lesson02/series.py | 3,379 | 4.4375 | 4 | #!/usr/bin/env python3
import time
def fibonacci(n=5):
"""Returns correlating value of position in Fibonacci series."""
# Fibonaccci Series: 0, 1, 1, 2, 3, 5, 8, 13, ...
if n == 0:
return 0
elif n == 1:
return 1
elif n > 1:
return fibonacci(n-2) + fibonacci(n-1)
def print_fibonacci_series(n=5):
"""Prints the Fibonacci series up to its nth value"""
for i in range(n):
print(fibonacci(i))
def lucas(n):
"""Returns correlating value of position in Lucas series."""
# Lucas Series: 2, 1, 3, 4, 7, 11, 18, 29, ...
if n == 0:
return 2
elif n == 1:
return 1
elif n > 1:
return lucas(n-2) + lucas(n-1)
def print_lucas_series(n=5):
"""Prints the Lucas series up to its nth value"""
for i in range(n):
print(lucas(i))
def sum_series(n, first=0, second=1):
"""Returns correlating value of parameter-passed index position in series.
The starting two positions are passed as the second and third parameters.
"""
if n == 0:
return first
elif n == 1:
return second
elif n > 1:
return sum_series(
n - 2, first, second) + sum_series(
n - 1, first, second)
def print_sum_series(n, first_value=0, second_value=1):
"""Prints a sum series from three params:
The first determines how many values to print
The second and third define the first two starting values
Defaults are set to 0, 1, so if no values are passed, Fibonacci is returned
"""
for i in range(n+1):
return sum_series(i, first_value, second_value)
if __name__ == "__main__":
# Test that functions match expected output of their known sequence
# Because class notes mentioned that the stack can get deep from recursion
# I was curious to see how long these tests take
# I imported the time module and set start var to before assert statements:
start = time.process_time()
# First, we test for Fibonacci outputs:
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(17) == 1597
assert fibonacci(29) == 514229
# Then, we test that my lucas() function outputs match
# known Lucas sequence values:
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
assert lucas(10) == 123
# Now, we test the generalized sum_series() function to see that
# it matches the Fibonacci sequence
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# And then we test it against the lucas() function
assert sum_series(5, 2, 1) == lucas(5)
# Now we'll test sum_series() against non-Fibonacci/Lucas sequences
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
# To determine how long the tests took,
# I want to capture the time after they finish:
elapsed_time = time.process_time() - start
# Now we'll calculate how long the test took
print("Test Successful. Completed in " + str(elapsed_time) + " seconds.")
|
dcb2fffbd28db53ea9346135bb86ad572f29543b | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/cbrown/Lesson 2/Complete_Fibonacci.py | 2,192 | 4.03125 | 4 | #Fibonacci Series Exercise
def fibonacci(n):
'''
returns the nth value of the fibonacci series
'''
#fibonacci sequence list
fib_seq = [0,1]
#fibonacci series counter
index = 0
if n == 0:
return fib_seq[0]
for i in range(n - 1):
new_fib_num = fib_seq[index] + fib_seq[index+1]
fib_seq.append(new_fib_num)
index = index + 1
return fib_seq[-1]
#Lucas Series Exercise
def lucas(n):
'''
returns the nth value of the fibonacci series
'''
#lucas sequence list
fib_seq = [2,1]
#lucas series counter
index = 0
if n == 0:
return fib_seq[0]
for i in range(n - 1):
new_fib_num = fib_seq[index] + fib_seq[index+1]
fib_seq.append(new_fib_num)
index = index + 1
return fib_seq[-1]
#Sum Series Exercise
def sum_series(n,x = 0,y = 1):
'''
returns the nth value of the fibonacci series
'''
#sequence list
fib_seq = [x,y]
#fibonacci series counter
index = 0
if n == 0:
return fib_seq[0]
for i in range(n - 1):
new_fib_num = fib_seq[index] + fib_seq[index+1]
fib_seq.append(new_fib_num)
index = index + 1
return fib_seq[-1]
if __name__ == "__main__":
#ensure fibonacci function returns correct values
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
#ensure lucas series returns correct values
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
#ensure fibonacci matches sum series
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print('tests passed')
|
7034f87f03b0321c6ebcb22c789ff62b8a3a028e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/david_baylor/lesson3/Mail_Room_part1.py | 2,002 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Mail_room_part1.py
By David Baylor on 12/3/19
uses python 3
Automates writing an email to thank people for their donations.
"""
def main():
data = [["bill", 100, 2, 50],["john",75, 3, 25]]
while True:
choice = input("""
What would you like to do?
1) Send a Thank You
2) Create a Report
3) Quit
""")
if choice == "1":
data = send_thank_you(data)
elif choice == "2":
creat_report(data)
elif choice == "3":
break
def send_thank_you(data):
name = input("Enter a full name or type 'list' to vew current list: ")
if name.upper() == "LIST":
for i in range(len(data)):
print(data[i][0].capitalize())
return data
else:
for i in range(len(data)):
if name.upper() == data[i][0].upper():
print("This personn has alredy donated add another donation under their name.")
donation = float(input(f"How much did {name.capitalize()} donate: $"))
data[i][1] += donation
data[i][2] += 1
data[i][3] = data[i][1]/data[i][2]
write_email(name, donation)
return data
donation = float(input(f"How much did {name.capitalize()} donate: $"))
data += [[name, donation, 1, donation]]
write_email(name, donation)
return data
def creat_report(data):
print("""
Donor Name | Total Given | Num Gifts | Average Gift
--------------------------|-------------|-----------|-------------""")
for i in range(len(data)):
make_row(data[i][0].capitalize(), data[i][1], data[i][2], data[i][3])
def make_row(name, total, num_gift, ave_gift):
print("{:26}|${:12}|{:11}|${:12}".format(name, total, num_gift, ave_gift))
def write_email(name, donation):
print("Here is the email:")
print(f"""
Dear {name.capitalize()},
Thank you for your generous donnation of ${donation}.""")
main()
|
df127e011ff7a1b1e4fe37869d5e87a248980101 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/allen_maxwell/Lesson_04/mailroom.py | 5,995 | 4.0625 | 4 | #!/usr/bin/env python3
# Allen Maxwell
# Python 210
# 12/3/2019
# Part 2
# mailroom.py
import os
def menu():
'''
Creates a user input menu selection.
Input: None
Output: None '''
# Loops through the menu options until the user selects 3, to quit
while True:
response = input('\n'.join(('\n',
'Please choose from the following options:',
'1) Create a Report',
'2) Send a Thank You letter to a single donor',
'3) Send a Thank You letter to all donors',
'4) Quit',
'Please enter your selection > ')))
menu_func(response)
def menu_func(selection):
'''
Processes menu input using dictionary values for switching.
Input: String: numeric value
Output: None'''
# Check if selection is a valid input
if not selection.isnumeric() or int(selection) not in menu_dict:
print('\nPlease enter a number 1 - 4')
else:
# Gets and calls the value associated with the selection
menu_dict.get(int(selection))()
def sort_key(values):
'''
Sorts the dictionary by values.
Input: Dictionary: values
Output: Dictionary: sorted values'''
return values[1][0]
def print_report():
'''
Prints a sorted list of your donors, sorted by total historical donation amount.
Input: None
Output: Display: formatted donor list'''
# Create Report Header
print('\n{:<19}{:3}{:12}{:3}{:10}{:3}{:<10}'
.format('Donor Name', '|', 'Total Given', '|', 'Num Gifts', '|', 'Average Gift'))
print('-'*62)
# Print donor list into a table format
for name, donor in sorted(donors.items(), key = sort_key, reverse = True):
print('{:<21}${:>11,.2f}{:^16}${:>11,.2f}'.format(name, *donor))
def thank_you():
'''
Creates a Thank You letter for a donor.
Input: None
Output: None'''
found = False
while not found:
# Prompt for a full name of the donor, list of donor names, or quit to menu
response = input("\nPlease enter the full name of the donor, 'List' for a list of donors,"
" or 'Quit' to exit to the menu > ")
# Exit to main menu if 'quit' is entered
if response.lower() == 'quit':
menu()
# If input value is empty
if response == '':
print('\nPlease enter a name')
# If response is list show a list of donor names and reprompt
elif response.lower() == 'list':
for donor in sorted(donors):
print(donor)
else:
# If the response name is on the list prompt for donation amount
if donors.get(response.title()) and not found:
add_donation(response.title())
found = True
# If the response name is not on list add it and prompt for donation amount
if not found:
add_donation(response.title(), True)
found = True
def add_donation(donor, is_new = False):
'''
Appends or adds a donation to the donor list.
Input: String: name, Boolean: is_new
Output: Display: Thank You letter'''
# Check for valid entry or quit
while True:
# Prompt user for a donation amount
donation = input("Please enter the amount of the donation for {} or 'Quit' to exit to the main menu > $ ".format(donor))
# Exit to main menu if 'quit' is entered
if donation.lower() == 'quit':
menu()
elif donation.isnumeric():
break
else:
print("Please enter a numeric value")
# Convert the donation amount to a float
donation = float(donation)
donor_data = ()
# Set new donor data values
if is_new:
donor_data = [0, 0, 0]
# Get current donor values
else:
donor_data = donors.get(donor)
# Calculate sum, number donations, and the average donation
sum_donations = donor_data[0] + donation
num_donations = donor_data[1] + 1
avg_donation = sum_donations / num_donations
# Add amount to the donor's donation history
donors.update({donor : [sum_donations, num_donations, avg_donation]})
# Print the thank you email
print(format_letter(donor, donation))
def format_letter(name, donation):
'''
Formats an email thanking the donor for their donation.
Input: String: name, Float: donation
Output: String: Formatted thank you letter'''
donor = {'first_name': name.split()[0], 'last_name': name.split()[1].strip(','), 'amount': donation}
return('''\n
Dear {first_name} {last_name},\n
Thank you so much for your generous gift of ${amount:,.2f}!\n
Your donation will go far in helping so many orphaned kittens and puppies find a new home.\n
Thank You,
Paws'''.format(**donor))
def thank_all():
'''
Formats and saves a letter thanking all the donor for their donations.
Input: None
Output: Files: Formatted thank you letters'''
for donor in donors:
first_name = donor.split()[0]
last_name = donor.split()[1].strip(',')
# Creates file and path
file_path = os.path.join("./{}_{}.txt".format(first_name, last_name))
# Opens and writes the Thank You letter to the file
with open(file_path, 'w+') as new_file:
new_file.write(format_letter(donor, donors.get(donor)[0]))
print('\nTask Complete')
def quit():
'''
Exit the program
Input: None
Output: Exit to terminal'''
print('\nGood Bye!\n\n')
exit()
# Creates a single donor dictionary
donors = {
'William Gates, III': [653784.49, 2, 326892.24],
'Mark Zuckerberg': [16396.10, 3, 5465.37],
'Jeff Bezos': [877.33, 1, 877.33],
'Paul Allen': [708.42, 3, 236.14],
'Steve Jobs': [10000.00, 1, 10000.00]}
# Creates a global menu dictionary
menu_dict = {
1: print_report,
2: thank_you,
3: thank_all,
4: quit,}
if __name__ == "__main__":
menu()
|
34c3ad9f2aaaa6e83e863724cb3a7fd5c03318e6 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/roslyn_m/lesson07/Lesson07_Notes.py | 1,632 | 4.28125 | 4 | class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay): # "self" refers to automatically taking in the instance
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
# 2 ways to call fullname:
emp_1.fullname()
Employee.fullname(emp_1)
# Class Variables: variables that are shared among all instances of a class
# while instance variables can be unique for each instance like our names and email and pay
# class variables should be the same for each instance
print(Employee.__dict__)
print(emp_1.__dict__)
Employee.raise_amt = 1.04 # can set raise amount by class
emp_1.raise_amt = 1.09 # can set it for one instance specifically
# Now call properties, and you will see emp_1 has raise amt
print(Employee.__dict__)
print(emp_1.__dict__)
print(Employee.raise_amt)
print(emp_1.raise_amt)
print(emp_2.raise_amt)
# class method vs Static methods
# When working with classes..... reg methods pass instance as the first argument, class methods automatically pass class as first.
# static method dont pass anything (no class or instance). Behave just like reg functions, but we include thm in our classes because they pertian to class
# If you dont access instance or the class, it should prob be an @staticmethod
print(vars(emp_1)) #gives attributes of an instance |
d299bb80ff5ce871c90f7d5e2733e8e93482d5d1 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/becky_larson/lesson03/3.1slicingLab.py | 2,622 | 4.1875 | 4 | #!/usr/bin/env python """
"""Exchange first and last values in the list and return"""
"""learned that using = sign, they refer to same object, so used copy."""
""" Could also use list command"""
"""tuple assert failing: RETURNING: (32, (54, 13, 12, 5, 32), 2). """
""" How to remove the parans"""
"""Is there a way to use same code for both string and tuple?"""
def exchange_first_last(seq):
if(type(seq)) == str:
a_new_sequence = seq[len(seq)-1] + seq[1:(len(seq)-1)] + seq[0]
else:
a_new_sequence = []
a_new_sequence.append(seq[len(seq)-1])
a_new_sequence.extend(seq[1:(len(seq)-1)])
a_new_sequence.append(seq[0])
print("RETURNING: ", a_new_sequence)
return tuple(a_new_sequence)
def remove_everyother(seq):
a_new_sequence = seq[::2]
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def remove_1stLast4_everyother(seq):
a_new_sequence = seq[4:-4:2]
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def elements_reversed(seq):
a_new_sequence = seq[::-1]
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def each_third(seq):
thirds = len(seq)/3
start1 = 0
end1 = int(thirds)
start2 = int(thirds)
end2 = int(thirds*2)
start3 = int(thirds*2)
end3 = int(thirds*3)
str1 = seq[start1:end1]
str2 = seq[start2:end2]
str3 = seq[start3:end3]
a_new_sequence = str3 + str1 + str2
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def run_assert():
# print("run_assert")
# assert exchange_first_last(a_string) == "ghis is a strint"
# print("string passed")
# assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2)
# print("tuple passed")
# assert remove_everyother(a_string) == "ti sasrn"
# print("string passed")
# assert remove_everyother(a_tuple) == (2, 13, 5)
# print("tuple passed")
# assert remove_1stLast4_everyother(a_string) == " sas"
# print("string passed")
# assert remove_1stLast4_everyother(a_tuple) == ()
# print("tuple passed")
# assert elements_reversed(a_string) == "gnirts a si siht"
# print("string passed")
# assert elements_reversed(a_tuple) == (32, 5, 12, 13, 54, 2)
# print("tuple passed")
assert each_third(a_string15) == "strinthis is a "
print("string passed")
assert each_third(a_tuple) == (5, 32, 2, 54, 13, 12)
print("tuple passed")
a_string15 = "this is a strin"
a_string = "this is a string"
a_tuple = (2, 54, 13, 12, 5, 32)
if __name__ == "__main__":
run_assert()
# each_third(a_tuple)
|
5d4e6f69b7d8774ad92b2e8c76a42692e3965f7a | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/travis_nelson/lesson04/mailroom_part2.py | 5,130 | 3.9375 | 4 | #!/usr/bin/env python3
import sys
donor_db = {"William Gates, III": [653772.32, 12.17],
"Jeff Bezos": [877.33, 3, 555, 132, 77, 1],
"Paul Allen": [663.23, 43.87, 1.32],
"Mark Zuckerberg": [1663.23, 4300.87, 10432.0],
"Brax Dingle": [2331, 32322.87, 5566.20, 3323.23, 76, 323, 3.87],
}
def single_thank_you():
"""Prints a letter to user-specified donor,
including recent and historical donation amounts"""
recipient = recipient_response()
donation = donation_response(recipient)
store_new_donation(recipient, donation)
total_donations = sum_donations(recipient)
print("Dearest {},\n"
"We are writing to formally thank you for your generous"
" donation of ${}.\n"
"To date, you have donated ${} to our honorable mission.\n"
"You are truly a valuable patron, and we thank you"
" for your service"
" (and money)".format(recipient, donation, total_donations))
def recipient_response():
"""Returns a recipient from the user...
If recipient was not previously in donor database, they are added"""
keep_asking = True
while keep_asking:
response = input("To whom should we address this Thank You?\n"
"(Type 'list' to view existing donors)\n").title()
if response.lower() == "list":
for i in donor_db:
print("{}".format(i))
else:
donor_exists = False
for donor in donor_db:
if donor == response:
donor_exists = True
if donor_exists:
print("An existing patron\n")
return response
else:
print("A new donor!\n")
donor_db[response] = []
return response
def donation_response(donor):
"""Returns the donation amount from the user"""
keep_asking = True
while keep_asking:
donation = input("How much did they donate?\n")
try:
if float(donation):
print("Nice!\n")
keep_asking = False
return donation
except ValueError:
print("Try again")
def store_new_donation(donor, donation):
"""Stores the donation amount in the donor database"""
updated_donations = donor_db[donor]
updated_donations.append(float(donation))
donor_db[donor] = updated_donations
def sum_donations(donor_name):
"""Returns sum of all historical donor donations"""
return round(sum(donor_db[donor_name]), 2)
def sort_key(donor):
"""Returns the key to sort donations by"""
return round(sum(donor_db[donor]))
def create_report():
"""Prints a list of all the donors, their total donation amount,
the total number of donations they've made,
and the average donation amount,
in descending order based on total amount given"""
sorted_donor_db = sorted(donor_db, key=sort_key, reverse=True)
str_header_formatting = "{:^20}|" * 4
str_grid_formatting = "-" * 21*4
print(str_header_formatting.format(
"Donor Name", "Total Given", "Num Gifts", "Average Gift"))
print(str_grid_formatting)
for i in sorted_donor_db:
donor_name = i
donor_total = round(sum(donor_db[i]), 2)
number_donations = len(donor_db[i])
average_donation = round(donor_total/number_donations)
print("{:20} ${:>19} {:>20} ${:>20}".format(
donor_name, donor_total, number_donations, average_donation))
def generate_all_thanks():
for i in donor_db:
most_recent_donation = ''.join(str(e) for e in donor_db[i][-1:])
with open(f'{i}.txt', 'w') as f:
f.write("Dearest {},\n"
"We are writing to formally thank you for your most recent"
" donation of ${}.\n"
"To date, you have donated ${} to our honorable mission.\n"
"You are truly a valuable patron, and we thank you "
"for your service (and money).\n"
"{}\n"
"{}".format(i,
most_recent_donation,
sum_donations(i),
"Kindest regards,",
"Baron Von Munchausen"))
def exit_program():
"""Exits the interactive script"""
print("Ok Bye!")
sys.exit()
def main():
"""Continuously asks the user for next task"""
prompt = "\n".join((">>>",
"Let's do some stuff!",
"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",
">>> "))
arg_dict = {"1": single_thank_you, "2": create_report,
"3": generate_all_thanks, "4": exit_program}
while True:
response = input(prompt)
arg_dict.get(response, "Try again!")()
if __name__ == "__main__":
main()
|
29eb66a3f5a8698c35b85b26135e129407eedfcb | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Deniss_Semcovs/Lesson02/series_01.py | 1,055 | 4.09375 | 4 | # Fibonacci series
def fibonacci(n):
"""This function will return series of numbers with range(n)
through Fibonacci Series starting with the integers 0 and 1."""
fn = 0
sn = 1
nn = 0
for i in range(n):
while nn < n:
print(fn)
nth = fn+sn
fn = sn
sn = nth
nn += 1
# Lucas series
def lucas(n):
"""This function will return series of numbers with range(n)
through Lucas Numbers starting with 2 and 1."""
fn = 2
sn = 1
nn = 0
for i in range(n):
while nn < n:
print(fn)
nth = fn+sn
fn = sn
sn = nth
nn += 1
# Sum Series
def sum_series(n, n0=0, n1=1):
"""This function will return series of numbers with range(n)
using optional numbers n0 and n1, by default n0 = 0 and n1 = 1."""
fn = n0
sn = n1
nn = 0
for i in range(n):
while nn < n:
print(fn)
nth = fn+sn
fn = sn
sn = nth
nn += 1
|
4193283059319b0e8c62b8c1b7ae597505106fbe | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/esokada/lesson05/mailroom3.py | 2,850 | 3.625 | 4 | #imports
import sys
from statistics import mean
from operator import itemgetter
# data structure
donors = {"Usagi":[12.5, 11.17, 130.1], "Ami":[17, 230, 2115], "Rei":[510.1, 50], "Makoto": [324, 22.7], "Minako": [310] }
#functions
def send_thankyou():
while True:
donorname = input("Please input a name, 'list' command, or 'c' to cancel:\n")
if donorname == "c":
return
elif donorname == "list":
print(donors.keys())
else:
while True:
donationamount = input("Please enter a donation amount:\n")
try:
if donationamount == "c":
return
if donorname in donors:
donors[donorname].append(float(donationamount))
break
else:
donors.update({donorname: [float(donationamount)]})
break
except ValueError:
print("Please enter the donation amount as a number.")
letterdict = {"donor_name": donorname, "donation_amount": float(donationamount)}
print("Dear {donor_name}, thank you for your generous donation of ${donation_amount:.2f}.\n".format(**letterdict))
break
def write_report():
titles = ["Donor Name", "Total Given", "Num Gifts", "Average Gift"]
print(f"{titles[0]:15} {titles[1]:>20} {titles[2]:>10} {titles[3]:>20}")
#this seemed to be the only place to use a list comprehension:
reportlines = [[k, sum(v), len(v), sum(v)/len(v)] for k, v in donors.items()]
for r in sorted(reportlines, key=itemgetter(1), reverse = True):
print(f"{r[0]:15} {r[1]:>20.2f} {r[2]:>10} {r[3]:>20.2f}")
def batch_letters():
for k, v in donors.items():
filetext = f"Dear {k},\nThank you for your donation of ${v[-1]:.2f}. Your total donations to date are ${sum(v):.2f}.\nWe appreciate your generosity to our organization.\nThanks, the Management."
with open(f"{k}.txt", "w") as f:
f.write(filetext)
def quit_program():
print("Goodbye!")
sys.exit()
#menus
def menu_selection(main_prompt, main_dispatch):
while True:
response = input(main_prompt)
try:
main_dispatch[response]()
except KeyError:
print("Please enter a number that corresponds to a menu option.")
#prompts
main_prompt = ("Select an action: 1 - Send a Thank You, 2 - Create a Report, 3 - Generate letters to all donors, or 4 - Quit\nReturn to main menu any time by entering 'c'\n")
main_dispatch = {"1": send_thankyou,
"2": write_report,
"3": batch_letters,
"4": quit_program
}
if __name__ == "__main__":
menu_selection(main_prompt, main_dispatch) |
05fe0c6cd5a9136f7c94df7bcbba087e851793ea | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/josh_embury/lesson02/fizzbuzz.py | 574 | 4.15625 | 4 | #--------------------------------------------------------------#
# Title: Lesson 2, FizzBuzz
# Description: Print the words "Fizz" and "Buzz"
# ChangeLog (Who,When,What):
# JEmbury, 9/18/2020, created new script
#--------------------------------------------------------------#
for i in range (1,101):
if i%3==0 and i%5==0: # check if divisible by 3 and 5
print("FizzBuzz")
elif i%3==0: # check if divisible by 3
print("Fizz")
elif i%5==0: # check if divisible by 5
print("Buzz")
else:
print(str(i)) # else print current number |
cc7d247a8465df3b60af2df620cb06e033ef4abb | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jim_krecek/lesson04/trigram.py | 1,451 | 3.890625 | 4 | import random
import re
trigram = 'I wish I may I wish I might'
words = trigram.split()
# builds list of words from txt file
def read_in_data(filename):
fulltext = []
with open(filename,'r') as text:
for line in text:
line = re.sub('--',' ',line)
line = line.strip('(')
line = line.strip(')')
for word in line.split():
fulltext.append(word.lower())
return fulltext
# tests creation of a trigram
def build_trigram(words):
trigrams = {}
for i in range(len(words[:-2])):
key = "{} {}".format(words[i],words[i+1])
val = words[i+2]
if key in trigrams:
trigrams[key].append(val)
else:
trigrams[key] = [val]
return trigrams
def write_story(word_pairs):
story = ''
start = random.choice(list(word_pairs.keys()))
pairs = start
while start in word_pairs:
pairs = "{} {}".format(pairs,word_pairs[start][random.randint(0,len(word_pairs[start])-1)])
story = ' '.join(pairs.split()[-2:])
start = story
# if len(story) >= 1000:
# break
return pairs
def write_file(story_text):
with open("my_story.txt", "w+") as outfile:
outfile.write(story_text)
if __name__ == "__main__":
text = read_in_data('sherlock_small.txt')
word_pairs = build_trigram(text)
story_text = write_story(word_pairs)
write_file(story_text) |
34ded0d22efe7ba1b6f7f42c86ff9bb19bc314bf | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jim_krecek/lesson05/mailroom_p3.py | 2,230 | 3.859375 | 4 | import sys
data = {"Nate Secinaro":[12,44,9],"Jess Reid":[3],"Pat Carrier":[65,41],"Zac Fisher":[13,4,4],"Jim Krecek":[3,33,57]}
prompt = "\nWhat do you want to do?\n -1 Send a Thank You\n -2 Create a Report\n -3 Send letters to all donors\n -4 Quit\n>>> "
def send_ty():
askname = input("\nEnter the full name of the donor or type 'list' to see the list of donors:\n>>> ")
if askname.lower() == "list":
print("\nHere is a list of all of the donors:")
[print(d) for d in data.keys()]
else:
askmoney = input("\nHow much did this person donate?\n>>> ")
try:
data[askname].append(int(askmoney))
except:
data[askname] = []
data[askname].append(int(askmoney))
emailtext = "\nDear {},\n\nThank you for your generous donation of ${}.\n\nSincerely, Jim".format(askname,askmoney)
print(emailtext)
def create_report():
firstline = "{:<25}| {:<12}| {:<10}| {:>12}".format("Donor Name", "Total Given", "Num Gifts", "Average Gift")
print(firstline)
print("-"*len(firstline))
sorted_data = sorted(((sum(value),len(value),key) for (key,value) in data.items()), reverse=True)
for tot,num,name in sorted_data:
average = tot/num
print("{:<25s} ${:>11.2f} {:>10d} ${:>12.2f}".format(name,tot,num,average))
def send_all():
for k,v in data.items():
lettertext = "Dear {},\n\n\tThank you for your very kind donation of ${}\n\n\tIt will be put to very good use.\n\n\t\t\tSincerely,\n\t\t\t\t-Jim & The Team".format(k,sum(v))
with open('{}.txt'.format(k.replace(' ','_')),'w+') as output:
output.write(lettertext)
print("\nLetters have been printed and are saved in the current directory")
def quit():
print('You are exiting the program. Come back again soon!')
sys.exit()
def main():
main_menu = {'1': send_ty,'2': create_report,'3':send_all,'4':quit}
while True:
response = input(prompt)
menu_function = main_menu.get(response)
try:
menu_function()
except TypeError:
print("\n'{}' is not a valid entry. Please try again.".format(response))
if __name__ == "__main__":
main() |
a34e999823473f4232a5c76750588660f7a299b5 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/josh_embury/lesson03/mailroom.py | 3,389 | 3.8125 | 4 | lst_donor_table = [
['Henry Michalson', 10, 500, 25],
['Phil Hutch', 76],
['Galileo Humpkins', 22000, 100, 490],
['Methusela Honeysuckle', 18, 69, 76000],
['Lavender Goombs', 55000, 25],
['test', 1]
]
def show_menu():
# shows user list of options
# return is void
""" Display a menu of choices to the user
:return: nothing
"""
print('''
Menu of Options
1) Send a Thank You
2) Create a Report
3) quit
''')
print() # Add an extra line for looks
def get_user_choice():
# asks user for choice
# returns integer value of user's choice
""" Gets the menu choice from a user
:return: string
"""
choice = str(input("Which option would you like to perform? [1 to 3] - ")).strip()
print() # Add an extra line for looks
return choice
def send_thank_you():
lst_donors = []
for current_donor in lst_donor_table:
lst_donors.append(current_donor[0])
donor = ''
while(len(donor) < 1):
donor = input('Please enter full name of donor >>> ')
if donor == 'list':
print(lst_donors)
donor = ''
new_donation = int(input('Please enter the donation amount >>> '))
if donor in lst_donors:
for i in range(0, len(lst_donors)):
if lst_donors[i] == donor:
lst_donor_table[i].append(new_donation)
else:
lst_donor_table.append([donor, new_donation])
str_thankyou = f'Thank you, {donor} for the generous gift of {new_donation}. You are incredibly nice.'
print(str_thankyou)
def get_donor_data(donor_name):
for current_donor in lst_donor_table:
if current_donor[0] == donor_name:
lst_gifts = current_donor[1:]
return [sum(lst_gifts), len(lst_gifts), sum(lst_gifts)/len(lst_gifts)]
def sort_donor_table(input_list):
lst_donation_totals = []
for item in input_list:
lst_donation_totals.append(get_donor_data(item[0])[0])
lst_donation_totals.sort()
copy_donor_table =list(input_list)
sorted_list = []
n = 0
while(n < len(input_list)):
for item in copy_donor_table:
if get_donor_data(item[0])[0] == lst_donation_totals[-1]:
sorted_list.append(item)
lst_donation_totals.pop(-1)
copy_donor_table.pop(copy_donor_table.index(item))
n += 1
return sorted_list
def format_row(info_list):
return '{:<26} {:<2} {:10.2f} {:>11} {:^2} {:10.2f}'.format(info_list[0],info_list[1],info_list[2],info_list[3], info_list[4], info_list[5])
def create_report():
header = '{:<25} {:^10} {:^10} {:^10}'.format('Donor Name', '| Total Given', '| Num Gifts', '| Average Gift')
print(header)
print('------------------------------------------------------------------')
# sort the donor table
lst_sorted_donor_table = sort_donor_table(lst_donor_table)
for current_donor in lst_sorted_donor_table:
donor_data = get_donor_data(current_donor[0])
new_row = [current_donor[0], '$', donor_data[0], donor_data[1], "$", donor_data[2]]
print(format_row(new_row))
if __name__ == '__main__':
while(True):
show_menu() # Shows menu
strChoice = get_user_choice() # Get menu option
if (strChoice.strip() == '1'):
send_thank_you()
elif(strChoice.strip() == '2'):
create_report()
elif(strChoice == '3'):
break # and exit
|
b7ea5ad4a6e38adb9a1f531b03348d24c21b3d24 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mgummel/lesson05/exceptions_lab.py | 394 | 3.703125 | 4 | #!/usr/bin/env python3
def safe_input():
""" Gets a file name from the user. Raises exceptions
if the user tries to quit ungracefully
"""
try:
get_file = input("Enter filename:\n>>>")
except KeyboardInterrupt:
return None
except EOFError:
return None
else:
print("No errors encountered!")
if __name__=='__main__':
safe_input() |
01e09084cf585a4fa00f87f743e25dd1d71128df | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/kristoffer_jonson/lesson3/mailroom.py | 3,259 | 3.765625 | 4 | #!/usr/bin/env python3
import sys
donor_db = [("William", [653772.32, 12.17]),
("Jeff", [877.33]),
("Paul", [663.23, 43.87, 1.32]),
("Mark", [1663.23, 4300.87, 10432.0]),
("Elon", [234.25, 2764.87, 9783.0]),
]
def main(donor_db):
"""
Prompts user for navigation of donor database
:param donor_db: Database of donations and donors
"""
prompt = "\n".join(("Donor Database",
"Please choose from below options (i.e. 2):",
"1 - Send a Thank You",
"2 - Create a Report",
"3 - Quit",
">>> "))
while True:
response = input(prompt)
if response == "1":
donor_db = thank_you(donor_db)
elif response == "2":
create_report(donor_db)
elif response == "3":
sys.exit()
else:
print("Not a valid option!")
def thank_you(donors):
"""
Enter donor data
:param donor_db: Database of donations and donors
"""
prompt = "\n".join(("Enter full name of donor",
"(Type list to diplay current donors):"))
response = input(prompt)
donor_list = []
donation = []
for i in range(len(donors)):
donor_list.append(donors[i][0])
if response.lower() == 'list':
for i in range(len(donors)):
print(donors[i][0])
elif response in donor_list:
current_donor = response
donation = enter_donation(donors, response)
create_card(response,donation)
else:
donors.append((response,[]))
donation = enter_donation(donors, response)
create_card(response,donation)
return donors
def enter_donation(donors, donator):
"""
Add donation data to donor
:param donor: Name of donator
:param donor: Amount of donation
"""
prompt = "\n".join(("Enter amount of donation",
"(No leading $ required):"))
donation = input(prompt)
donation = float(donation)
for donor in donors:
donor[1].append(donation)
return donation
def create_card(donator, amount):
"""
Create thank you card text
:param donor: Name of donator
:param donor: Amount of donation
"""
card_text = ['Dear {}:','','Thank you for your generosity in your gift of ${:.2f}. It will go long way in supporting this charity.','']
card_text = card_text + ['Sincerely,','','','','Kristoffer Jonson']
card_text = "\n".join(card_text)
print(card_text.format(donator,amount))
return True
def create_report(donors):
"""
Print formatted report of donors and amounts donated
:param donor_db: Database of donations and donors
"""
print('Donor Name | Total Given | Num Gifts | Average Gift')
print('------------------------------------------------------------------')
format_string = '{:<26} $ {:>11.2f}{:>12d} $ {:>11.2f}'
donors = sorted(donors,key=sort_key,reverse=True)
for i in range(len(donors)):
print(format_string.format(donors[i][0],sum(donors[i][1]),len(donors[i][1]),sum(donors[i][1])/len(donors[i][1])))
def sort_key(donors):
return sum(donors[1])
if __name__ == '__main__':
main(donor_db)
|
c28354828f26d6285ac455873abbe17ca68c0d2a | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/andrew_garcia/lesson_02/series.py | 2,455 | 4.21875 | 4 | '''
Andrew Garcia
Fibonacci Sequence
6/9/19
'''
def fibonacci(n):
""" Computes the 'n'th value in the fibonacci sequence, starting with 0 index """
number = [0, 1] # numbers to add together
if n == 0:
return(number[0])
elif n == 1:
return(number[1])
else:
for item in range(n - 1): # subtracts 1 to account for 0 index
fib = number[0] + number[1]
number.append(fib)
number.pop(0)
return(number[1])
def lucas(n):
""" Computes the 'n'th value in the lucas sequence, starting with 0 index """
number = [2, 1] # numbers to add together
if n == 0:
return(number[0])
elif n == 1:
return(number[1])
else:
for item in range(n - 1): # subtracts 1 to account for 0 index
fib = number[0] + number[1]
number.append(fib)
number.pop(0)
return(number[1])
def sum_series(n, zeroth=0, first=1):
"""
Computes the 'n'th value in a given series
:param zeroth=0: Creates the first value to use in a series
:param first=1: Creates the second value to use in a series
If the two parameters are left blank, or are filled in 0 and 1, it will start the fibonacci sequence
If the two parameters are filled in 2 and 1, it will start the lucas sequence
If the two parameters are filled in with two random numbers, it will create its own sequence
"""
number = [zeroth, first] # numbers to add together
if n == 0:
return(number[0])
elif n == 1:
return(number[1])
else:
for item in range(n - 1): # subtracts 1 to account for 0 index
fib = number[0] + number[1]
number.append(fib)
number.pop(0)
return(number[1])
if __name__ == "__main__":
# Tests if Fibonacci is working
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(5) == 5
assert fibonacci(9) == 34
print('Fibonacci Working')
# Tests if lucas is working
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(2) == 3
assert lucas(5) == 11
assert lucas(9) == 76
print('Lucas Working')
# Tests random sequences
assert sum_series(0) == 0
assert sum_series(1, 0, 1) == 1
assert sum_series(0, 2, 1) == 2
assert sum_series(4, 2, 3) == 13
assert sum_series(1, 5, 7) == 7
print('Series Working')
|
1fe321426c14d3bdedf0f0d8737d6cb09bd9544c | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/srmorehouse/Lesson02/series.py | 3,549 | 4.1875 | 4 | #!/usr/bin/env python3
"""
fibonacci
input: n : series in the fibonacci series
return: if 0, 0
if 1, 1
else (n-2)+(n-1)
No negative number error checking
"""
def fibonacci(n):
if n == 0:
retVal = 0
elif n == 1:
retVal = 1
else:
retVal = fibonacci(n - 2) + fibonacci(n - 1)
return retVal
"""
lucas
input: n : series in the lucas series
return: if 0, 2
if 1, 1
else (n-2)+(n-1)
No negative number error checking
"""
def lucas(n):
if n == 0:
retVal = 2
elif n == 1:
retVal = 1
else:
retVal = lucas(n - 2) + lucas(n - 1)
return retVal
"""
sum_series
inputs:
n is the fibonacci/lucas series number
firstVal is the optional zeroth value (default zero)
secondVal is the optional first value (default one)
output:
fibonacci (default)
No negative number error checking
"""
def sum_series(n, firstVal=0, secondVal=1):
if n == 0:
retVal = firstVal
elif n == 1:
retVal = secondVal
else:
retVal = sum_series(n - 2, firstVal, secondVal) + sum_series(n - 1, firstVal, secondVal)
return retVal
if __name__ == '__main__':
# print out values to verify
for x in range(0, 10):
print('fibonacci of ' + str(x) + ' is ' + str(fibonacci(x)))
# now assert
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
for x in range(0, 10):
print('fibonacci sum_series of ' + str(x) + ' is ' + str(sum_series(x)))
# now assert sum_series
assert sum_series(0) == 0
assert sum_series(1) == 1
assert sum_series(2) == 1
assert sum_series(3) == 2
assert sum_series(4) == 3
assert sum_series(5) == 5
assert sum_series(6) == 8
assert sum_series(7) == 13
for x in range(0, 10):
print('lucas of ' + str(x) + ' is ' + str(lucas(x)))
# now assert
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
for x in range(0, 10):
print('lucas sum_series of ' + str(x) + ' is ' + str(sum_series(x, 2, 1)))
# now assert sum_series
assert sum_series(0, 2, 1) == 2
assert sum_series(1, 2, 1) == 1
assert sum_series(2, 2, 1) == 3
assert sum_series(3, 2, 1) == 4
assert sum_series(4, 2, 1) == 7
assert sum_series(5, 2, 1) == 11
assert sum_series(6, 2, 1) == 18
assert sum_series(7, 2, 1) == 29
# run some more tests
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("tests passed")
|
b159c6b75befa81b3fecd3a208d6ad2f4bbcb873 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/lee_deitesfeld/lesson03/strformat_lab.py | 2,058 | 4.21875 | 4 | #Task One - Write a format string that will take a tuple and turn it into 'file_002 : 123.46, 1.00e+04, 1.23e+04'
nums = 'file_%03d : %.2f, %.2E, %.2E' % (2, 123.4567, 10000, 12345.67)
print(nums)
#Task Two
def f_string(name, color, ice_cream):
'''Takes three arguments and inserts them into a format string'''
favorite = f"My name is {name}. My favorite color is {color}, and my favorite ice cream flavor is {ice_cream}."
print(favorite)
#Task Three
def formatter(seq):
'''Writes a function that displays "The __ numbers are: __, __, etc" '''
length = len(seq)
print(("The {} numbers are: " + ", ".join(["{}"] * length)).format(length, *seq))
#Task Four
def num_pad(seq):
'''Converts (4, 30, 2017, 2, 27) to "02 27 2017 04 30" '''
lst = []
#return nums in sequence padded with zeroes
for num in seq:
lst.append(f'{num:02}')
#convert list to string with no commas
first_str = (' '.join(lst))
first = first_str[0:6]
middle = first_str[6:11]
last = first_str[11:]
#print final string
print(last + ' ' + middle + first)
#Task Five - Display 'The weight of an orange is 1.3 and the weight of a lemon is 1.1'
fruits = ['oranges', 1.3, 'lemons', 1.1]
f_str = f'The weight of an {(fruits[0])[:-1]} is {fruits[1]} and the weight of a {(fruits[2])[:-1]} is {fruits[3]}.'
print(f_str)
#Then, display the names of the fruit in upper case, and the weight 20% higher
f_str_bonus = f'The weight of an {((fruits[0])[:-1]).upper()} is {fruits[1]*1.2} and the weight of a {((fruits[2])[:-1]).upper()} is {fruits[3]*1.2}.'
print(f_str_bonus)
#Task Six - print a table of several rows, each with a name, an age and a cost
for line in [["Name", "Age", "Cost"], ["Lee", 33, "$56.99"], ["Bob", 62, "$560.99"], ["Harry", 105, "$5600.99"], ["Jeanne", 99, "$56099.99"]]:
print('{:>8} {:>8} {:>8}'.format(*line))
#Then, given a tuple with 10 consecutive numbers, print the tuple in columns that are 5 charaters wide
tup = (1,2,3,4,5,6,7,8,9,10)
for x in tup:
print('{:>5}'.format(x), end= " ")
|
85a5d0342785c2ec20cf90f527a59dbb74491093 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/altaf_lakhi/lesson_02/grid_printer.py | 1,400 | 3.625 | 4 | def grid_printer():
plus = ('+ ' + ('- ' * 4)) * 2
tally = ('|' + (' ' * 9)) * 3
print(plus, end='+')
print()
print(tally)
print(tally)
print(tally)
print(tally)
print(plus, end='+')
print()
print(tally)
print(tally)
print(tally)
print(tally)
print(plus, end='+')
grid_printer(3)
def grid_printer_2 (n):
x = n//2
y = n+1
for i in range(1):
print('+' + (' -' * x) + ' +' + (' -' * x) + ' +')
for i in range(x):
if n % 2 >= 1:
print('|' + (' ' * n) + '|' + (' ' * n) + '|')
else:
print('|' + (' ' * y) + '|' + (' ' * y) + '|')
for i in range(1):
print('+' + (' -' * x) + ' +' + (' -' * x) + ' +')
for i in range(x):
if n % 2 >= 1:
print('|' + (' ' * n) + '|' + (' ' * n) + '|')
else:
print('|' + (' ' * y) + '|' + (' ' * y) + '|')
for i in range(1):
print('+' + (' -' * x) + ' +' + (' -' * x) + ' +')
#grid_printer_2(15)
def grid_printer_3 (n,z):
for i in range (0,n):
for i in range(0,n):
print('+', ('- ' * z), end=' ')
print('+')
for i in range(0,z):
for i in range(0,n):
print('|', (' ' * (z*2)), end=' ')
print('|')
for i in range(0,n):
print('+', ('- ' * z), end=' ')
print('+')
#grid_printer_3(3,4) |
3103efdd0a71f2e3ff3b20261aa2f7179f421d67 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/steve-long/lesson02-basic-functions/ex-2-1-grid-printer/gridPrinter.py | 9,190 | 4.34375 | 4 | #!/usr/bin/env python3
# ========================================================================================
# Python210 | Fall 2020
# ----------------------------------------------------------------------------------------
# Lesson02
# Grid Printer Exercise (gridPrinter.py)
# Steve Long 2020-09-20 | v0
#
# Requirements:
# -------------
#
# (Paraphrased due to pictorial nature of requirements and mix of non-requirement subject
# matter.)
#
# Part 1: Write a function that renders an NxN cell grid to stdio with "-" for the
# horizontal cell edge, "|" for the vertical cell edge, "+" for cell nodes (intersections
# of horizontal and vertical cell edges.)
#
# Part 2: Write a function print_grid(n) that takes one integer argument and prints a grid
# just like before, but the size of the NxN cell grid is given by the argument, n. This is
# an underspecified requirement that allows some degree of freedom.
#
# Part 3: Write a function print_grid2(n,m) similar to print_grid that takes an integer
# argument n for the number of grid cells, and m for the number of characters for the
# horizontal and vertical side of each cell. This is also an underspecified requirement
# that allows some degree of freedom.
#
# Implementation:
# ---------------
#
# Part 1 and 2 are implemented in function print_grid. Part 3 is implemented in
# function print_grid2. The main (script-level) method calls print_grid2 and uses
# several helper methods to provide default and preferred values. Both print_grid and
# print_grid2 both call the general method makeGrid to create the grid string.
#
# Script Usage:
# -------------
#
# python gridPrinter.py [<cellCount> [ <cellSize>]]
# <cellCount> ::= Number of grid cells.
# <cellSize> ::= Number of characters (not counting nodes) on a cell side.
#
# Issues:
# -------
#
# If Python has something akin to Java's StringBuffer class, this would probably be
# a good candidate for its use.
#
# History:
# --------
# 000/2020-09-20/sal/Created.
# ========================================================================================
import sys
def minCellCount():
"""
minCellCount()
--------------------------------------------------------------------------------------
Minimum number of cells N to draw for an NxN grid.
Exit: Returns int value > 0.
"""
return 1
def cellCountDefault():
"""
cellCountDefault()
--------------------------------------------------------------------------------------
Default number of cells N to draw for an NxN grid.
Exit: Returns int value > 0.
"""
return 2
def minCellSize():
"""
minCellSize()
--------------------------------------------------------------------------------------
Smallest number of characters M for a cell edge on an NxN grid (not counting node
character).
Exit: Returns int value > 0.
"""
return 1
def cellSizeDefault():
"""
cellSizeDefault()
--------------------------------------------------------------------------------------
Default number of characters M for a cell edge on an NxN grid (not counting node
character).
Exit: Returns int value > 0.
"""
return 4
def edgeCharHDefault():
"""
edgeCharHDefault()
--------------------------------------------------------------------------------------
Default character for a cell horizontal edge on an NxN grid (not counting node
character).
Exit: Returns single char.
"""
return "-"
def edgeCharVDefault():
"""
edgeCharVDefault()
--------------------------------------------------------------------------------------
Default character for a cell vertical edge on an NxN grid (not counting node
character).
Exit: Returns single char.
"""
return "|"
def nodeCharDefault():
"""
nodeCharDefault()
--------------------------------------------------------------------------------------
Default character where cell horizontal and vertical edges intersect on an NxN grid.
Exit: Returns single char.
"""
return "+"
def isValidNodeChar(nodeChar):
"""
isValidNodeChar(<nodeChar>)
--------------------------------------------------------------------------------------
Validation rule for node character on NxN grid.
Entry: <nodeChar> ::= A single character.
Exit: Returns True if valid.
"""
valid = (len(nodeChar) == 1)
return valid
def isValidEdgeCharH(edgeCharH):
"""
isValidEdgeCharH(<edgeCharH>)
--------------------------------------------------------------------------------------
Validation rule for cell horizontal edge character on NxN grid.
Entry: <edgeCharH> ::= A single character.
Exit: Returns True if valid.
"""
valid = (len(edgeCharH) == 1)
return valid
def isValidEdgeCharV(edgeCharV):
"""
isValidEdgeCharV(<edgeCharV>)
--------------------------------------------------------------------------------------
Validation rule for cell vertical edge character on NxN grid.
Entry: <edgeCharV> ::= A single character.
Exit: Returns True if valid.
"""
valid = (len(edgeCharV) == 1)
return valid
def gridLineEdgeH(cellCount, cellSize, nodeChar, edgeCharH):
"""
gridLineEdgeH(<cellCount>, <cellSize>, <nodeChar>, <edgeCharH>)
--------------------------------------------------------------------------------------
Draw a horizontal line for the grid.
Entry: <cellCount> ::= Grid cell count (N).
<cellSize> ::= Grid cell edge size.
<nodeChar> ::= Character for grid node.
<edgeCharH> ::= Character for cell horizontal edge.
Exit: Returns string rendering for grid horizontal line.
"""
s = nodeChar
for i in range(0, cellCount):
s = "{}{}{}".format(s, (edgeCharH * cellSize), nodeChar)
return s
def gridLineEdgeV(cellCount, cellSize, nodeChar, edgeCharV):
"""
gridLineEdgeV(<cellCount>, <cellSize>, <nodeChar>, <edgeCharV>)
--------------------------------------------------------------------------------------
Draw a vertical line for the grid.
Entry: <cellCount> ::= Grid cell count (N).
<cellSize> ::= Grid cell edge size.
<nodeChar> ::= Character for grid node.
<edgeCharV> ::= Character for cell vertical edge.
Exit: Returns string for grid vertical line.
"""
s = edgeCharV
for i in range(0, cellCount):
s = "{}{}{}".format(s, (" " * cellSize), edgeCharV)
return s
def makeGrid(cellCount, cellSize, nodeChar, edgeCharH, edgeCharV):
"""
makeGrid(<cellCount>, <cellSize>, <nodeChar>, <edgeCharH>, <edgeCharV>)
--------------------------------------------------------------------------------------
Build the string need to rend an NxN grid.
Entry: <cellCount> ::= Grid cell count (N). No less than minCellCount().
<cellSize> ::= Grid cell edge size. No less than minCellCount().
<nodeChar> ::= Single character for grid node.
<edgeCharH> ::= Single character for cell horizontal edge.
<edgeCharV> ::= Single character for cell vertical edge.
Exit: Returns string for grid. Invalid argument values are replaced by minimum or
default values.
"""
cellCount = max(minCellCount(), cellCount)
cellSize = max(minCellSize(), cellSize)
nodeChar = nodeChar if isValidNodeChar(nodeChar) else nodeCharDefault()
edgeCharH = edgeCharH if isValidEdgeCharH(edgeCharH) else edgeCharHDefault()
edgeCharV = edgeCharV if isValidEdgeCharV(edgeCharV) else edgeCharVDefault()
s = gridLineEdgeH(cellCount, cellSize, nodeChar, edgeCharH) + "\n"
for i in range(0,cellCount):
for j in range(0,cellSize):
s = s + gridLineEdgeV(cellCount, cellSize, nodeChar, edgeCharV) + "\n"
s = s + gridLineEdgeH(cellCount, cellSize, nodeChar, edgeCharH) + "\n"
return s
def print_grid(cellCount):
"""
print_grid(<cellCount>)
--------------------------------------------------------------------------------------
Draw an N-cell grid.
Entry: <cellCount> ::= Grid cell count (N).
Exit: Renders NxN grid with default cell edge size to standard output.
"""
s = makeGrid(cellCount, cellSizeDefault, nodeCharDefault(), edgeCharHDefault(), edgeCharVDefault())
print(s)
def print_grid2(cellCount, cellSize):
"""
print_grid2(<cellCount>, <cellSize>)
--------------------------------------------------------------------------------------
Draw an N-cell grid of M-sized cells.
Entry: <cellCount> ::= Grid cell count (N).
<cellSize> ::= Grid cell edge size (M).
Exit: Renders Renders NxN grid with specified cell edge size to standard output.
"""
s = makeGrid(cellCount, cellSize, nodeCharDefault(), edgeCharHDefault(), edgeCharVDefault())
print(s)
# Command-line interface for demonstrating function print_grid2.
#
# Usage: python gridPrinter.py [<cellCount> [ <cellSize>]]
if __name__ == "__main__":
msg = ""
argvCount = len(sys.argv)
if (argvCount > 3):
print("Ignoring extra arguments")
args = [cellCountDefault(), cellSizeDefault()]
ok = True
#
# Check for invalid input; substitute with default values if not specified.
#
for i in range(1,min(len(sys.argv),3)):
if (not sys.argv[i].isnumeric()):
msg = msg + "\ngridPrinter (ERROR): Arg {} ({}) not an integer".format(i,sys.argv[i])
ok = False
else:
args[i-1] = abs(int(sys.argv[i]))
if ok:
#
# Draw grid OR...
#
cellCount = args[0]
cellSize = args[1]
print_grid2(cellCount,cellSize)
else:
#
# ...print error message.
#
print(msg[1:])
|
141ecb109a74426ebc0662694a25ffab054abc60 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/asotelo/lesson02/fizz_buzz_exercise.py | 454 | 4.0625 | 4 | #!/usr/bin/python3
'''
Author: Alex Sotelo
Exercise 2.3
Python 3 required
Requirement: https://uwpce-pythoncert.github.io/PythonCertDevel/exercises/fizz_buzz.html
'''
def fizz_buzz(i):
if i%3 == 0 and i%5 !=0:
print('Fizz')
elif i%5 == 0 and i%3 !=0:
print('Buzz')
elif i%3 == 0 and i%5 == 0:
print('FizzBuzz')
else:
print(i)
def print_range(x,y):
for i in range(x,y):
fizz_buzz(i)
print_range(1,101) |
e0df8a46d6104c5e6d8fbf0868ee19acb67df13d | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/nskvarch/Lesson6/mailroom4.py | 5,807 | 4.09375 | 4 | #!/usr/bin/env python3
# Lesson 5 exercise "the mailroom part 3", created by Niels Skvarch
# Import Modules needed to run
import sys
import os
# define global variables
donor_db = {"Bob Johnson": [3772.32, 512.17],
"Fred Billyjoe": [877.33, 455.50, 23.45],
"Harry Richard": [1.50],
"Old Gregg": [1663.23, 4300.87, 10432.0],
"Jerry Vars": [19.95, 653.21, 99.45],
}
menu = ("\n".join(("Welcome to the Mailroom.",
"Please choose from below options:",
"1 - Add a new contribution and display sample thank you letter",
"2 - Display a donor Report",
"3 - Create a thank you letter for all donors",
"4 - Exit",
"--> ")))
# define functions
def print_report(data_lines):
"""Take in a table in the form of a list and display it"""
sizes = [0] * len(data_lines[0])
for line in data_lines:
for item_index, item in enumerate(line):
if len(item) > sizes[item_index]:
sizes[item_index] = len(item)
for line in data_lines:
print(line[0].ljust(sizes[0]) + " $ " + line[1].ljust(sizes[1]) + " " + line[2].rjust(
sizes[2]) + " \t " + line[3].rjust(sizes[3]))
print("\n")
def run_report():
"""take in the donor database, create organize and sort a table in the form of a list and then hand the table off
to the printer function """
data_lines = []
for name in donor_db:
data = donor_db[name]
data_lines.append((name, str(sum(data)), str(len(data)), str(sum(data) / len(data))))
to_print = [("Name", "Total Donated", "Times Donated", "Average Donation")] + \
sorted(data_lines, key=lambda x: float(x[1]), reverse=True)
print_report(to_print)
def thanks(data_base):
"""create a thank you note customized to the name provided,
if the name was not in the donor database already, add the name and prompt for a donation amount"""
while True:
response = input("\nPlease enter the name of the person donating or type 'List' for a list of donors: ")
amount = ()
if response.lower() == "list":
run_report()
else:
while True:
try:
amount = float(input("\nPlease enter the amount donated: "))
break
except ValueError:
print("\nOops! Something went wrong. Please enter a numerical value.")
for donor_name in data_base:
if response.lower() == donor_name.lower():
data_base[donor_name].append(amount)
print_thankyou(donor_name)
return data_base
donor_name = add_new_donor(data_base, response, amount)
print_thankyou(donor_name)
return data_base
def print_thankyou(donor_name):
"""Takes in the name and donation amount and organizes the values into a sample thank you letter and displays
it on the screen """
nl = "\n"
print(f"Dear {donor_name},{nl}" +
f" Thank you for your donation of $ {donor_db[donor_name][-1]}. We {nl}" +
f"appreciate your contribution.{nl}{nl} Your total donation amount is now " +
f"$ {sum(donor_db[donor_name])}.{nl}{nl}" +
f"Sincerely,{nl}" +
f"Your Charity of Choice"
)
def create_thankyou_all():
"""Takes in the name and donation amount for all donors and creates a thank you text document
in the same folder the program is run from for each donor, unless a specific directory is specified"""
nl = "\n"
custom = input("Press Enter to create the letters in the directory the Mailroom has been run from"
" or type 'custom' to specify a directory")
# I had to get creative here as the error catch needs to come before
# the Open operator so I can request input again rather than a try loop around the 'with open'
if custom != "":
while True:
customdir = input("Please specify a custom directory path: ")
tested = os.path.exists(customdir)
if tested == True:
break
elif tested == False:
print("That directory or path does not exist, please specify a valid directory")
cwd = customdir
elif custom == "":
cwd = os.getcwd()
for donor_name in donor_db:
filename = donor_name.replace(" ", "") + ".txt"
full_filename = os.path.join(cwd, filename)
with open(full_filename, 'w') as f:
f.write(f"Dear {donor_name},{nl}" +
f" Thank you for your donation of $ {donor_db[donor_name][-1]}. We {nl}" +
f"appreciate your contribution.{nl}{nl} Your total donation amount is now " +
f"$ {sum(donor_db[donor_name])}.{nl}{nl}" +
f"Sincerely,{nl}" +
f"Your Charity of Choice"
)
def add_new_donor(data_base, name, amount):
"""add a donor not in the donor database to the database"""
data_base.update({name: [amount]})
return name
def exit_program():
"""use the sys module to clean-exit the script"""
print("Good bye")
sys.exit()
def main():
""""main loop for the program to occupy while running, includes the main menu"""
while True:
response = input(menu)
switch_dict = {"1": lambda db=donor_db: thanks(db), "2": run_report, "3": create_thankyou_all}
if response in switch_dict:
switch_dict[response]()
elif response == "4":
exit_program()
else:
print("Not a valid option!")
# main program name-space
if __name__ == "__main__":
main()
|
52bfbc84cb6ce5ad8e31973566dc323bcaa24b30 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jinee_han/lesson08/circle.py | 4,209 | 4.4375 | 4 | #!/usr/bin/env python3
from math import pi
class Circle:
'''
A circle class
'''
def __init__(self, radius_value):
''' Initialize a new instance of the Circle class '''
self.radius = radius_value
@property
def diameter(self):
'''
Diameter property
:return: the diameter of the circle
'''
return self.radius * 2
@diameter.setter
def diameter(self, diameter_value):
'''
Set the diameter value
:param diameter_value: the diameter value
:return: nothing
'''
self.radius = diameter_value / 2
@property
def area(self):
'''
The circle area property
:return: The area of the circle
'''
return pi * self.radius ** 2
@classmethod
def from_diameter(cls, diameter_value):
'''
The diameter constructor
:param diameter_value: The diameter value of the circle
:return: a Circle object specified with the desired diameter / radius
'''
return cls(diameter_value / 2)
def __str__(self):
'''
Override the string method
:return: The desired string format
'''
return "Circle with radius: {}".format(self.radius)
def __repr__(self):
'''
Override the representation method
:return: The desired representation
'''
return "Circle({})".format(self.radius)
def __add__(self, other):
'''
Override the add method
:param other: The other object to add
:return: a Circle with the current radius added to the other radius
'''
return Circle(self.radius + other.radius)
def __mul__(self, other):
'''
Override the multiplication method
:param other: The other scalar to multiply
:return: a Circle with the current radius multiplied by the other factor
'''
return Circle(self.radius * other)
def __gt__(self, other):
'''
Override the greater than method
:param other: The other object to compare
:return: True if self is greater than other radius
'''
return self.radius > other.radius
def __ge__(self, other):
'''
Override the greater than or equal method
:param other: The other object to compare
:return: True if self is greater than or equal to other radius
'''
return self.radius >= other.radius
def __lt__(self, other):
'''
Override the less than method
:param other: The other object to compare
:return: True if self is less than other radius
'''
return self.radius < other.radius
def __le__(self, other):
'''
Override the less than or equal than method
:param other: The other object to compare
:return: True if self is less than or equal to other radius
'''
return self.radius <= other.radius
def __eq__(self, other):
'''
Override the equal method
:param other: The other object to compare
:return: True if two objects are equal, false if not
'''
return self.radius == other.radius
class Sphere(Circle):
'''
A sphere subclass derived from a Circle class
'''
def __str__(self):
'''
Override the string method
:return: The sphere's string formatting
'''
return "Sphere with radius: {}".format(self.radius)
def __repr__(self):
'''
Override the representation method
:return: The sphere's representation
'''
return "Sphere({})".format(self.radius)
@property
def volume(self):
'''
Calculate the volume of a sphere
:return: The volume of a sphere for the given radius
'''
# volume of a sphere is: 4/3 pi r^3
return 4 / 3 * pi * self.radius ** 3
@property
def area(self):
'''
Calculate the surface area
:return: the surface area for the given radius
'''
return 4 * pi * self.radius ** 2
|
2d1f7265bd7c027d42254a0ae390577ee339f630 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/gregdevore/lesson03/slicing_lab.py | 4,028 | 4.28125 | 4 | # Various functions to practice sequence slicing
def exchange_first_last(seq):
""" Return sequence with first and last items swapped. """
if len(seq) <= 1: # Edge case for empty or single sequence -> return sequence
return seq
else:
# Use slicing even on single items to ensure all are sequences
return seq[-1:] + seq[1:-1] + seq[:1]
def remove_every_other(seq):
""" Return sequence with every other item removed. First item will be kept. """
return seq[::2]
def return_every_other_between_first_last_4(seq):
""" Return sequence with every other item between first four and last four. """
return seq[4:-4:2]
def reverse_sequence(seq):
""" Return sequence with items reversed. """
return seq[::-1]
def swap_thirds(seq):
""" Return sequence with last third, first third, middle third, in that order. """
# Be aware that for sequences whose length is not evenly divisible by three,
# abs(-len(seq)//3) != len(seq)//3, so results may be different than expected.
return seq[-len(seq)//3:] + seq[:-len(seq)//3]
if __name__ == '__main__':
# Test edge cases (empty or single item) and normal cases
empty_str = ''
really_short_str = 'a'
short_str = 'ab'
normal_str = 'There is nothing permanent except change'
empty_list = []
really_short_list = [1]
short_list = [1,2]
normal_list = [1,2,3,4,5,6]
long_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
assert exchange_first_last(empty_str) == ''
assert exchange_first_last(really_short_str) == 'a'
assert exchange_first_last(short_str) == 'ba'
assert exchange_first_last(normal_str) == 'ehere is nothing permanent except changT'
assert exchange_first_last(empty_list) == []
assert exchange_first_last(really_short_list) == [1]
assert exchange_first_last(short_list) == [2,1]
assert exchange_first_last(normal_list) == [6,2,3,4,5,1]
assert remove_every_other(empty_str) == ''
assert remove_every_other(really_short_str) == 'a'
assert remove_every_other(short_str) == 'a'
assert remove_every_other(normal_str) == 'Teei ohn emnn xetcag'
assert remove_every_other(empty_list) == []
assert remove_every_other(really_short_list) == [1]
assert remove_every_other(short_list) == [1]
assert remove_every_other(normal_list) == [1,3,5]
assert return_every_other_between_first_last_4(empty_str) == ''
assert return_every_other_between_first_last_4(really_short_str) == ''
assert return_every_other_between_first_last_4(short_str) == ''
assert return_every_other_between_first_last_4(normal_str) == 'ei ohn emnn xetc'
assert return_every_other_between_first_last_4(empty_list) == []
assert return_every_other_between_first_last_4(really_short_list) == []
assert return_every_other_between_first_last_4(short_list) == []
assert return_every_other_between_first_last_4(normal_list) == []
assert return_every_other_between_first_last_4(long_list) == [4, 6, 8, 10, 12, 14]
assert reverse_sequence(empty_str) == ''
assert reverse_sequence(really_short_str) == 'a'
assert reverse_sequence(short_str) == 'ba'
assert reverse_sequence(normal_str) == 'egnahc tpecxe tnenamrep gnihton si erehT'
assert reverse_sequence(empty_list) == []
assert reverse_sequence(really_short_list) == [1]
assert reverse_sequence(short_list) == [2,1]
assert reverse_sequence(normal_list) == [6,5,4,3,2,1]
assert swap_thirds(empty_str) == ''
assert swap_thirds(really_short_str) == 'a'
assert swap_thirds(short_str) == 'ba'
assert swap_thirds(normal_str) == ' except changeThere is nothing permanent'
assert swap_thirds(empty_list) == []
assert swap_thirds(really_short_list) == [1]
assert swap_thirds(short_list) == [2,1]
assert swap_thirds(normal_list) == [5,6,1,2,3,4]
assert swap_thirds(long_list) == [13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print('All tests passed.')
|
f5546f8ee7b79dfa119e2e08e76bdc0bf5494789 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Kollii/lesson04/dict_lab.py | 1,951 | 4.21875 | 4 | #!/usr/bin/env python3
# Lesson 4 - DictLab
# DICTIONARY 1
dict1 = {
'name': 'Chris',
'city': 'Seattle',
'cake': 'Chocolate',
}
print(" This is original Dictionary \n")
print(dict1)
print("\nCake Element removed from Dictionary")
print(dict1.pop("cake"))
print('\n fruit = Mango added added to Dictionary')
dict1['fruit'] = 'Mango'
print(dict1)
print('\n Display the dictionary keys.')
for x in dict1:
print(x)
print('\n Display the dictionary values.')
for x in dict1:
print(dict1[x])
print('Is cake in the Dictionay-dict1 ? {}'.format('cake' in dict1.keys()))
print('Is Mango in Dictionay-dict1 ? {}'.format('Mango' in dict1.values()))
####### DICTIONARY 2 ##############
dict2 = {
'name': 'Chris'.count('t'),
'city': 'Seattle'.count('t'),
'cake': 'Chocolate'.count('t'),
}
print('\n Dictionary with the number of ‘t’s in each value as the value \n ')
print(dict2)
# SET 1
s2 = set()
s3 = set()
s4 = set()
for x in range(0,20):
if x%2 == 0:
s2.update([x])
for x in range(0,20):
if x%3 == 0:
s3.update([x])
for x in range(0,20):
if x%4 == 0:
s4.update([x])
print('\n**** SET- s2 ******')
print("s2 contains numbers from zero through twenty, divisible by 2 {} ", s2)
print('\n**** SET- s3 ******')
print("s2 contains numbers from zero through twenty, divisible by 3 {} ", s3)
print('\n**** SET- s4 ******')
print("s2 contains numbers from zero through twenty, divisible by 4 {} ", s4)
print('\nis s3 is a subset of s2 ---', s3.issubset(s2))
print('\nis s4 is a subset of s2 ---', s4.issubset(s2))
# SET 2
set_str = {'P','y','t','h','o','n'}
set_str.add('i')
set_frz = frozenset(['m','a','r','a','t','h','o','n'])
print('\n******* UNION OF set PHYTHON and frozenset MARATHON ***********')
print(set_str.union(set_frz))
print('\n******* INTERSECTION OF set PHYTHON and frozenset MARATHON ***********')
print(set_str.intersection(set_frz))
|
77e8ab6231d164cf55dc365626189e4a9f5fa0ac | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/clifford_butler/lesson01/break_me.py | 412 | 3.5 | 4 | # the following function will give you a NameError
def name_error():
a = 2
print (a)
# the following function will give you a TypeError
def type_error():
b = '4' + 3
type_error()
# the following function will give you a SyntaxError
def syntax_error()
c = 4
syntax_error()
# the following function will give you a AttributeError
def attribute_error():
d = 3
print(attribute_error.d)
|
3bc82c02bc4a26db706f0cbcf4a772b96ede820a | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/adam_strong/lesson03/list_lab.py | 1,715 | 4.25 | 4 | #!/usr/bin/env python3
##Lists##
fruits = ['Apples', 'Pears', 'Oranges', 'Peaches']
fruits_original = fruits[:]
## Series 1 ##
print('')
print('Begin Series 1')
print('')
print(fruits)
response1 = input("Please add another fruit to my fruit list > ")
fruits.append(response1)
print(fruits)
response2 = input("Type a number and I will return that fruit's number")
#response2 = int(response2)
print('Fruit number: ', response2, ' ', fruits[int(response2)-1])
response3 = input("Please add another fruit to the beginning of my fruit list > ")
fruits = [response3] + fruits
print(fruits)
response4 = input("Please add another fruit to the beginning of my fruit list > ")
fruits.insert(0, response4)
print(fruits)
print('All the fruits that begin with "P"')
for fruit in fruits:
if fruit[0] == "P":
print(fruit)
##Series 2 ##
print('')
print('Begin Series 2')
print('')
print(fruits)
fruits = fruits[:-1]
print(fruits)
response5 = input("Please type a fruit to remove from the list > ")
fruits.remove(response5)
print(fruits)
##Series 3
print('')
print('Begin Series 3')
print('')
fruits2 = fruits[:]
for fruit in fruits:
while True:
yn = input("Do you like " + fruit.lower() + '?. Type yes or no.')
if yn == 'no':
fruits2.remove(fruit)
break
elif yn == 'yes':
break
else:
input("Please type only yes or no in response.")
print(fruits2)
##Series 4 ##
print('')
print('Begin Series 4')
print('')
fruits_backwards = []
for fruit in fruits_original:
fruits_backwards.append(fruit[::-1])
fruits_original_minus = fruits_original[:-1]
print(fruits_backwards)
print(fruits_original)
print(fruits_original_minus)
|
0ef43998f3fbe99684e37811122d6f4d3bcde0e3 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mattcasari/lesson01/logic-1/in1to10.py | 234 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def in1to10(n, outside_mode):
if outside_mode and ( n <= 1 or 10 <= n):
return True
elif not outside_mode and 1 <= n <= 10:
return True
else:
return False |
b49cec4ce3542b3b57a60f408e684891b6ee267b | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mitch334/lesson08/sparse_array.py | 1,101 | 3.625 | 4 |
class SparseArray():
def __init__(self, array):
self.len = len(array)
self.sparse = {index: item for index, item in enumerate(array) if item}
self.array = array
def __len__(self):
return self.array_length
def __delitem__(self, index):
try:
del self.sparse[index]
except KeyError:
print('Unable to delete index', index)
def __getitem__(self, index):
if index >= 0 and index < self.len:
return self.sparse.get(index, 0)
elif index > self.len or index < 0:
print('Index', index, 'not in Array.')
return None
def __setitem__(self, index, value):
if value != 0:
self.sparse[index] = value
else:
try:
del self.sparse[index]
except KeyError:
print('Index', index, 'not in Array.')
def append(self, value):
if value != 0:
self.sparse[self.len] = value
self.len += 1
if __name__ == "__main__":
sa = SparseArray([1,2,0,0,0,0,3,0,0,4])
|
efcf95e1791fd8e1da6d97f40138b9205b4a918c | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/kimc05/Lesson04/mailroom2.py | 3,917 | 3.859375 | 4 | #!/usr/bin/env python3
import sys
#Paths and File Processing
import pathlib
pth = pathlib.Path("./")
pth.is_dir()
#get path
pth.absolute()
#Christine Kim
#Python210 Lesson 3 Mailroom Part 1
#Donor dictionary created
givetree = {("Rutherford", "Cullen"): (1500, 4200, 50000),
("Theirin", "Alistair"): (200, 80000, 1500000),
("Arainai", "Zevran"): (50,),
("Amell", "Solona"): (2, 500000, 2000000),
("Lavellan", "Soufehla"): (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\n"
"2: Create a Report\n"
"3: Send a Letter to All\n"
"4: Quit\n")
#method for menu selection
def menu(prompt, dispatch_dict):
while True:
#receive user input
response = input(prompt)
#direct user to proper function
dispatch_dict[response]()
#method for sending thank you to donor
def thank_you():
#receive user input donor full name
giver = 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.lower() == "list":
for last, first in givetree:
print("{} {}".format(first, last))
giver = input("\nPlease enter the full name of the donor in 'first last' format: ")
#prompt for donation amount
received = int(float(input("\nPlease enter the amount of donation: ")))
#split first/last name
first_last = giver.split(" ")
first_name = first_last[0].capitalize()
last_name = first_last[1].capitalize()
#Update Existing donor
if (last_name, first_name) in givetree:
new_entry = {(last_name, first_name): (givetree.get((last_name, first_name))) + (received,)}
givetree.update(new_entry)
#Add New donor
else:
givetree.setdefault((last_name, first_name), (received,))
#Compose gratitude email
print(email(first_name, last_name, received))
#Create donation histroy report for user
def report():
#print report 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))
#sort by donation total
sorted_Giver = sorted(givetree.items(), key=total_v, reverse=True)
#summarize value and print report content
for person in sorted_Giver:
#get name tuple
last_first = person[:1][0]
#Summarize value
total = total_v(person)
donation_num = len(person[1:])
average = total / donation_num
#print content
print("{:<14} {:<14}${:>15.2f}{:>10} ${:>15.2f}\n"
.format(last_first[1], last_first[0], total, donation_num, average))
#return the key for sorting = total amount of donation
def total_v(info):
return sum(info[1:][0])
def letters():
for l_name, f_name in givetree:
total = total_v(("empty", givetree.get((l_name, f_name))))
with open(f"{f_name}_{l_name}.txt", "w") as dest:
dest.write(email(f_name, l_name, total))
def email(first_name, last_name, amt):
#Compose gratitude email
thanks = (f"\nDear Ser {first_name} {last_name},\n"
f"Thank you for your generous donation of ${amt:,d}\n"
"We will make certain your goodwill is directed to aid those affected by the Fifth Blight.\n"
"With regards,\n"
"The Blight Orphans Charity,\n")
return thanks
#quit the script
def end():
print("\nThank you for your patronage. Farewell!\n")
sys.exit()
#main menu dictionary
menu_dict = {"1": thank_you,
"2": report,
"3": letters,
"4": end}
if __name__ == '__main__':
#initiate menu selection
menu(prompt, menu_dict)
|
8c2ebe4cc24b80cf94608e0782797dd96e89a1e1 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/zhen_yang/lesson07/html_render.py | 4,422 | 3.546875 | 4 | #!/usr/bin/env python3
"""
A class-based system for rendering html.
"""
# This is the framework for the base class
class Element(object):
tag_name = 'html'
indent = ' '# four spaces for indentation
#indent = ''# no space for indentation
def __init__(self, content=None, **kwargs):
if kwargs:
self.attributes_dict = kwargs
else:
self.attributes_dict = {}
if content is None:
self.content = []
else:
self.content = [content]
def append(self, new_content):
self.content.append(new_content)
def _open_tag(self, cur_ind=''):
tag_str = [f'{cur_ind}{self.indent}<{self.tag_name}']
for key, val in self.attributes_dict.items():
tmp_str = f' {key}="{val}"'
tag_str.append(tmp_str)
tag_str.append('>')
return "".join(tag_str)
def _close_tag(self, cur_ind=''):
return f'{cur_ind}{self.indent}</{self.tag_name}>\n'
#def render(self, out_file):
def render(self, out_file, cur_ind=''):
out_file.write(self._open_tag(cur_ind))
out_file.write('\n')
for content in self.content:
if isinstance(content, Element):# string element
content.render(out_file, cur_ind + self.indent)
elif isinstance(content, str):
out_file.write(f'{cur_ind}{self.indent*2}{content}\n')
else:# unknown objects
raise(AttributeError, "Unknown object.")
out_file.write(self._close_tag(cur_ind))
# Define subclasses 'Html', 'Body', 'P'
class Html(Element):
tag_name = 'html'
indent = ''
#def render(self, out_file):
def render(self, out_file, cur_ind=''):
#out_file.write(f'{cur_ind}{self.indent}<!DOCTYPE html>\n')
out_file.write(f'<!DOCTYPE html>\n')
super().render(out_file, cur_ind + self.indent)
class Body(Element):
tag_name = 'body'
class P(Element):
tag_name = 'p'
class Head(Element):
tag_name = 'head'
class OneLineTag(Element):
tag_name = 'title'
def append(self, new_content):
if len(self.content) == 0:
self.content.append(new_content)
else:
raise AttributeError("OneLineTag only has one content.")
def render(self, out_file, cur_ind=''):
out_file.write(self._open_tag(cur_ind))
# OneLineTag only allow single string content.
if isinstance(self.content[0], str):# string element
out_file.write(f'{self.content[0]}</{self.tag_name}>\n')
else:
print(f"content:{self.content}")
raise AttributeError("OneLineTag doesn't allow Object decalration")
class Title(OneLineTag):
tag_name = 'title'
class SelfClosingTag(Element):
tag_name = 'hr'
def __init__(self, content=None, **kwargs):
if content is None:
super().__init__(**kwargs)
else:
raise TypeError("SelfClosingTag doesn't allow content paramter.")
#def render(self, out_file):
def render(self, out_file, cur_ind=''):
out_file.write(f'{self._open_tag(cur_ind)[:-1]} />\n')
class Hr(SelfClosingTag):
tag_name = 'hr'
class Br(SelfClosingTag):
tag_name = 'br'
class A(Element):
tag_name = 'a'
def __init__(self, link=None, content=None, **kwargs):
if link is None:
self.link = 'https://www.python.org/'
else:
self.link = link
if content is None:
self.content = ['link to python']
else:
self.content = [content]
super().__init__(content, **kwargs)
def render(self, out_file, cur_ind=''):
out_file.write(f'{cur_ind}{self.indent}<{self.tag_name} \
href="{self.link}">{self.content[0]}</a>\n')
class H(OneLineTag):
tag_name = 'h'
def __init__(self, Tag_flag=-1, content=None, **kwargs):
if Tag_flag == -1:
raise (AttributeError, "H tag needs an integer \
argument for the header level.")
else:
if str(Tag_flag).isdigit():
self.tag_name = f'{self.tag_name}{Tag_flag}'
else:
raise (ValueError, "H tag needs an integer for header level.")
super().__init__(content, **kwargs)
class Ul(Element):
tag_name = 'ul'
class Li(Element):
tag_name = 'li'
class Meta(SelfClosingTag):
tag_name = 'meta'
|
96443f2a4b1c8f9e691773273bd51d1ff5cef792 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Pirouz_N/lesson03/strformat_lab.py | 4,097 | 4.40625 | 4 | #!/usr/bin/env python3
"""
Purpose: Lessen 3 homework three, string formatting lab, python certificate from UW
Author: Pirouz Naghavi
Date: 07/02/2020
"""
# imports
import random
import string
# Task One
print('Task one:')
input_tuple = (2, 123.4567, 10000, 12345.67)
# Printing results of converting input_tuple to: 'file_002 : 123.46, 1.00e+04, 1.23e+04'
print('file_{} : {:.2f}, {:.2e}, {:.3g}'
.format(format(input_tuple[0], '0>3'), input_tuple[1], input_tuple[2], input_tuple[3]))
# Task two
print('Task two:')
# Using f strings
print(f'file_{format(input_tuple[0], "0>3")} : {input_tuple[1]:.2f}, {input_tuple[2]:.2e}, {input_tuple[3]:.3g}')
# Task three
print('Task three:')
input_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print('Using format string:')
print('The {} numbers are: {}'.format(len(input_tuple), '{:d}, ' * (len(input_tuple) - 1) + '{:d}')
.format(*input_tuple))
print('Using f string:')
print(f'The {len(input_tuple)} numbers are: { str(input_tuple)[1:len(str(input_tuple))-1]}')
def formatter(nums):
""""This function string with length and elements in nums.
Args:
nums: Is the index that the fibonacci sequence will be generated until and the value of index
n will be returned.
Returns:
String including length and values inside of nums.
Raises:
ValueError: If nums is a None.
TypeError: If nums isn't a tuple.
"""
if nums is None:
raise ValueError('Tuple cannot be None.')
if not isinstance(nums, tuple):
raise TypeError('Input must be of type tuple.')
return f'The {len(nums)} numbers are: { str(nums)[1:len(str(nums))-1]}'
print('Using formatter function:')
print(formatter(input_tuple))
# Task four
print('Task four:')
input_tuple = (4, 30, 2017, 2, 27)
print(input_tuple[4])
# Using string formatting to print '02 27 2017 04 30'
print('Results: {} {} {} {} {}'.format(format(input_tuple[3], '0>2'),
input_tuple[4], input_tuple[2], format(input_tuple[0], '0>2'), input_tuple[1]))
print('Expected: 02 27 2017 04 30')
# Task five
print('Task five:')
input_list = ['oranges', 1.3, 'lemons', 1.1]
# Printing expected string using f string "The weight of an orange is 1.3 and the weight of a lemon is 1.1"
print(f'The weight of an {input_list[0][:len(input_list[0]) - 1]} is {input_list[1]} and the weight of a'
f' {input_list[2][:len(input_list[2]) - 1]} is {input_list[3]}')
# Printing expected result for comparison
print('Which is the same as:')
print("The weight of an orange is 1.3 and the weight of a lemon is 1.1")
# Printing updated result string using f string "The weight of an ORANGE is 1.56 and the weight of a LEMON is 1.32"
print('Next part:')
print(f'The weight of an {input_list[0][:len(input_list[0]) - 1].upper()} is {1.2 * input_list[1]} and the weight of a'
f' {input_list[2][:len(input_list[2]) - 1].upper()} is {1.2 * input_list[3]}')
# Printing expected result for comparison
print('Which is the same as:')
print("The weight of an ORANGE is 1.56 and the weight of a LEMON is 1.32")
# Task six
print('Task six:')
# Printing table
print('{:<20.20s}\t{:<20.20s}\t{:<20.20s}\t{:<20.20s}'.format('First Name', 'Last Name', 'Age', 'Cost'))
print('____________________________________________________________________________________________')
# Generating a table
for _ in range(50):
# Generating data randomly length of each field is limited to 20 characters
print('{:<20.20s}\t{:<20.20s}\t{:<20.20s}\t{:<20.20s}'
.format(''.join(random.choices(string.ascii_lowercase, k=random.randint(1, 100))).title(),
''.join(random.choices(string.ascii_lowercase, k=random.randint(1, 100))).title(),
str(random.randint(1, 100)), str(random.randint(1, 100000000000000000000))))
# Task 6 extra task
print('Task six extra:')
input_tuple = tuple([str(i) for i in range(1000, 1010)])
print('The {} numbers are: \n{}'.format(len(input_tuple), '{:<5.5s}\t' * (len(input_tuple))).format(*input_tuple))
|
a743e54784be7e57a94f8e5fa81b91137d897c04 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/steve-long/lesson04-dicts-sets-files/ex-4-3-simple-text-manip/trigrammatron.py | 17,470 | 4.53125 | 5 | #!/usr/bin/env python3
# =============================================================================
# Python210 | Fall 2020
# -----------------------------------------------------------------------------
# Lesson04
# Simple Text Manipulation (trigrammatron.py)
# Steve Long 2020-10-16 | v0
#
# Requirements:
# =============
#
# Trigrams
# --------
#
# Trigrams can be used to mutate text into new, surreal, forms. But what
# heuristics do we apply to get a reasonable result?
#
# The Problem
# -----------
#
# Trigram analysis is very simple. Look at each set of three adjacent words
# in a document. Use the first two words of the set as a key, and remember
# the fact that the third word followed that key. For example, given the
# input...
#
# I wish I may I wish I might
#
# ...will yield the following relationship...
#
# "I wish" => ["I", "I"]
# "wish I" => ["may", "might"]
# "may I" => ["wish"]
# "I may" => ["I"]
#
# To generate new text from this analysis, choose a word pair as a
# starting point. Use this pair of words to look up the list of next words,
# choose a random element from this list, and append it to the word pair
# to form a phrase...
#
# "I may I"
#
# Use the last two words of this phrase as the next key ("may I") which is
# mapped to word "wish". The next phrase becomes...
#
# "may I wish"
#
# For this exercise, try implementing a trigram algorithm that generates a
# couple of hundred words of text using a book-sized file as input.
#
# Objectives
# ----------
#
# The assignment includes using mapping data structures and determining the
# heuristics for processing the text. What do we do with punctuation?
# Paragraphs? Do we have to implement backtracking if we choose a next word
# that turns out to be a dead end?
#
# Developing Your Solution
# ------------------------
#
# This assignment has two parts: the trigrams exercise itself and the text
# processing to get a full book in shape for processing.
#
# A large data file is required for processing.
#
# The source text file may require cleanup prior
# to building the trigram map.
#
# There may be multiple occurrences of the 2-word pair mapped to different
# third words; capture all of the third words.
#
# Several additional cleanup operations may be implemented:
#
# - Strip out punctuation? - If you do this, what about contractions, i.e.
# the appostrophe in "can't" vs. a single quotation mark – which are the
# same character.
#
# - Remove capitalization? - If you do this, what about "I"? And proper
# nouns?
#
# - Any other ideas you may have.
#
# Assumptions:
# ============
#
# There is enough ambiguity in the requirements to allow a degree of
# artistic freedom. The implementation description reveals some of the
# choices.
#
# Implementation:
# ===============
#
# Trigrammatron sounded like an insidious title for the script, so I used it.
#
# The filtering the text file data is implemented with the goal of providing
# a set of words with minimal punctuation and symbolic characters (chars)
# in order to generate at least a few sensible phrases. Data is processed on
# a line basis, not with every word of the document chained together.
# chaining the entire document word list into a single list only generates
# additional nonsensical phrases. The word1+word2 key maps to a list
# of unique word3 values.
#
# *Output. The script accepts an input file name and provides the ability to
# use the the trigram data structure three different ways. See the
# documentation string for function run_trigrammatron_demo_ui below.
#
# *File clean-up. File cleanup is extensive. Sequences of allowed and
# disallowed substrings are collected into sets for checking and line, word,
# and character substitution. It does not include removing item numbers and
# certain other "technical" text (the marginal return on that time
# expenditure was not deemed worthwhile.)
#
# *Handling missing values. Function show_trigrams_haiku chains word 2 and 3
# of a trigram into the key for the next phrase. If there is no entry for
# that key (due to the word filtering process or because the word pair
# appeared at the end of a line) then the output terminates.
#
# Style. Function run_trigrammatron_demo_ui provides a crude user interface.
#
# Checked with flake8.
#
# Script Usage:
# =============
#
# ./trigrammatron.py
#
# Issues:
# =======
#
# Requirements description should be simpler (it's a long explanation
# for a simple concept).
#
# History:
# ========
# 000/2020-10-16/sal/Created.
#
# =============================================================================
import string
import random
import pathlib
from itertools import chain
from collections import defaultdict
# -- Generic functions --------------------------------------------------------
def is_blank(s):
"""
Is string blank?
"""
return (len(s) == 0)
def clean_string(s_in, delimiter):
"""
clean_string(<s>, <delimiter>)
------------------------------
Remove adjacent occurences of delimiter from a string.
Entry: <s> ::= (str) String to process.
<delimiter> ::= (str) One or more consecutive chars to split and
rejoin <s> on.
Exit: Returns <s> with adjacent <delimiter> removed.
"""
words = s_in.strip().split(delimiter)
s = []
for word in words:
if (not is_blank(word)):
s.append(word)
s_out = delimiter.join(s)
return s_out
# -- Char groups --------------------------------------------------------------
# ---- Non-alphanumeric symbols allowed on the INSIDE of a word ---------------
_Allowed_Symbols = ("(", ")", "[", "]", "{", "}", "<", ">", "\"", "'", "`",
"-", "_", "=", "|", "\\", "%", "$", "*", "@", "#", "~")
# ---- Non-alphanumeric symbols not allowed on the start or end of a word -----
_Disallowed_End_Symbols = ("-", "_", "=", "|", "\\", "%", "$", "*", "@", "#",
"~", ".", ",", "?", ":", ";", "!", "\"", "'",
"`", "(", ")", "[", "]", "{", "}", "<", ">")
# ---- Lines beginning or ending with these strings are discarded -------------
_Disallowed_Line_Ends = ("***",)
_All_Symbols = tuple(chain(_Allowed_Symbols, _Disallowed_End_Symbols))
_Allowed_Single_Letters = ("a", "I")
_Replacement_Symbols = (("_", " "), ("--", " "))
# -- Char sets ----------------------------------------------------------------
_Lowercase_Char_Set = set(string.ascii_lowercase)
_Allowed_Symbol_Set = set(_Allowed_Symbols)
_All_Symbol_Set = set(_All_Symbols)
_Allowed_Single_Letter_Set = set(_Allowed_Single_Letters)
_Disallowed_End_Symbol_Set = set(_Disallowed_End_Symbols)
# -- Word content tests -------------------------------------------------------
def is_symbols_only(s):
"""
Is string composed exclusively of symbols?
"""
result = True
for c in s:
if (c not in _All_Symbol_Set):
result = False
break
return result
def is_all_upper_case(s):
"""
Are all characters in a string uppercase letters?
"""
result = True
for c in s:
if (c in _Lowercase_Char_Set):
result = False
break
return result
# -- Display formatting -------------------------------------------------------
def format_word_one(word_in):
"""
Format the first word of a trigram phrase.
"""
word_out = word_in
if (not is_all_upper_case(word_in)):
word_out = word_in.capitalize()
return word_out
def format_word_one_plus(word_in):
"""
Format the second or third word of a trigram phrase.
"""
word_out = word_in
if (not is_all_upper_case(word_in)):
word_out = word_in.lower()
return word_out
def replace_substrings(line_in):
"""
Replace substrings found in the replacement sequence.
"""
# Rule: Certain strings identifiable as decorative in any context
# are replaced.
line_out = line_in
for fi, re in _Replacement_Symbols:
line_out = line_out.replace(fi, re)
return line_out
# -- Word editing -------------------------------------------------------------
def trim_disallowed_end_chars(word_in):
"""
Remove disallowed characters from the ends of a word.
"""
# Rule: Certain chars are removed from beginning or ending of words
# as extraneous.
word_out = word_in
n = 0
for i in range(0, len(word_out)):
c = word_out[i]
if (c in _Disallowed_End_Symbol_Set):
n = i + 1
else:
break
word_out = word_out[n:]
n = len(word_out)
for i in range((len(word_out)-1), 0, -1):
c = word_out[i]
if (c in _Disallowed_End_Symbol_Set):
n += -1
else:
break
return word_out[:n]
def scrub_word(word_in):
"""
Remove characters not allowed for the trigrammatron from a word.
Returns a word.
"""
#
# Rule: Certain chars are not allowed on the ends of words.
#
word_out = trim_disallowed_end_chars(word_in)
if (is_symbols_only(word_out)):
#
# Rule: Symbol chars alone do not constitute a word.
#
word_out = ""
else:
if (len(word_out) == 1):
#
# Rule: Single chars do not constitute a word.
#
if (word_out not in _Allowed_Single_Letter_Set):
word_out = ""
return word_out
def scrub_excluded_line(line_in):
"""
Null out entire line if it starts or ends with a diallowed string.
"""
# Rule: Lines beginning or ending in certain characters are entirely
# excluded from the construction set.
line_out = line_in
for lend in _Disallowed_Line_Ends:
if (line_in.startswith(lend)):
line_out = ""
break
elif (line_in.endswith(lend)):
line_out = ""
break
else:
continue
return line_out
# -- Line editing -------------------------------------------------------------
def scrub_line(line_in):
"""
Remove unsupported and unnecessary chars from a line of words.
Returns a list of words.
"""
words_out = []
line = scrub_excluded_line(clean_string(line_in, " "))
line = replace_substrings(line)
if (not is_blank(line)):
for word in line.split(" "):
word = scrub_word(word)
if (not is_blank(word)):
words_out.append(word)
return words_out
# -- Trigram driver -----------------------------------------------------------
def build_trigrams(source_pathname):
"""
Build a trigram dictionary from a list of words [word1,
word2, word3, wordN] where the key is (word|i|, word|i+1|)
and the value is [word|i+2|]. The list tracks multiple
third words mapped to the key.
"""
trigrams = defaultdict(list)
with open(source_pathname, 'r') as source_file:
while True:
line_in = source_file.readline()
if (not line_in):
break
else:
words = scrub_line(line_in)
for i in range(0, len(words)-2):
key = (words[i].lower(), words[i+1].lower())
values = trigrams[key]
value = words[i+2]
if (value not in values):
trigrams[key].append(value)
return trigrams
# -- Demo functions ----------------------------------------------------------
def show_contents_of_trigrams_a2z(trigrams):
"""
Show sorted 3-word phrases built from trigrams.
"""
for key in sorted(trigrams.keys()):
values = trigrams[key]
for value in sorted(values):
print("({} {}) => {}"
.format(key[0], key[1], value))
def show_trigrams_haiku(trigrams):
"""
Show 3-word phrases built from trigrams composed of the two
elements the tuple forming the key for the third word. The
first key is chosen randomly and the remaining phrases are
found thus:
phraseN: = wordN1, wordN2, r-trigrams[(wordN1 wordN2)]
= wordN1, wordN2, wordN3
phraseN+1 = wordN2, wordN3, r-trigrams[(wordN2 wordN3)]
where r-trigrams retrieves a random element from the list of
words mapped to (wordN1 wordN2).
Shows 3-word phrases until the next key does not map to a
value and displays 'No word keyed on {key}' OR the number
of allowed values is reached (to avoid user boredom.)
Allowing the function to terminate when no key is reached is
why data was processed on a per-line basis and does not chain
the entire file's word list together.
"""
random.seed()
#
# A counting mechanism is included because a user will probably get
# bored with this after 3000 nonsense phrases.
#
n = 1
max_n = 3000
msg = ""
keys = tuple(trigrams.keys())
key = random.choice(keys)
values = trigrams[key]
msg = (f"No word keyed on {key}" if (not values) else "")
while (values):
value = random.choice(values)
phrase = "{} {} {}".format(format_word_one(key[0]),
format_word_one_plus(key[1]),
format_word_one_plus(value))
print(phrase)
n += 1
key = (key[1], value.lower())
values = trigrams[key]
if (n > max_n):
#
# The threshold of user patience has been reached.
#
msg = f"Max iteration count ({max_n}) reached"
break
elif (not values):
#
# Phrase keychain broken.
#
msg = f"No word keyed on {key}"
else:
#
# Phrase keychain unbroken.
#
msg = ""
print(msg)
def show_trigrams_phrase_from_random_key(trigrams):
"""
Show 3-word phrase based on a random key and value from the
key's mapped value sequence in the trigrams dictionary.
One phrase is generated for each key in the trigrams structure.
"""
random.seed()
keys = tuple(trigrams.keys())
key_count = len(keys)
for n in range(0, key_count):
key = keys[random.randrange(0, key_count)]
values = trigrams[key]
if (values):
value = random.choice(values)
print("{} {} {}."
.format(format_word_one(key[0]),
format_word_one_plus(key[1]),
format_word_one_plus(value)))
else:
print("No word keyed on {}".format(key))
# -- Demo user interface -----------------------------------------------------
_CMD_HAIKU = ":HAIKU" # Command to generate chained 3-word phrases.
_CMD_RANDKEY = ":RANDKEY" # Command to generate random 3-word phrases.
_CMD_A2Z = ":A2Z" # Command to generate key-value pairs.
_CMD_EXIT = ":EXIT" # Command to exit app.
def choice_to_cmd(choice):
"""
Convert user input to specific command name.
"""
choice = choice.strip(" ")
cmd = None
if (choice.isnumeric()):
choice = int(choice)
if (choice == 1):
cmd = _CMD_HAIKU
elif (choice == 2):
cmd = _CMD_RANDKEY
elif (choice == 3):
cmd = _CMD_A2Z
else:
cmd = None
else:
choice = choice.upper()
if (choice[0:2] == ":X"):
cmd = _CMD_EXIT
return cmd
def run_trigrammatron_demo_ui():
"""
User interface for testing 'trigrammatron', a data structure for
storing condition trigram words from the text file
'a-prefects-uncle.txt'. User is presented with four choices:
[1] Haiku: The trigram is used to generate what looks like a
crazy haiku of chained 3-word phrases with the first word
capitalized.
[2] Random Key: Generates random 3-word phrases.
[3] A-to-Z: Pairs of key and each value in alphabetical order.
[:X] Exit for user interface.
"""
print("\nTrigrammatron Demo\n")
prompt = "Enter text document filename > "
source_pathname = input(prompt)
source_path = pathlib.Path(source_pathname)
if (source_path.exists()):
source_pathname = str(source_path)
trigrams = build_trigrams(source_pathname)
prompt = "[1] Haiku, [2] Random Key, [3] A-to-Z, e[:X]it > "
cmd = None
while (cmd != _CMD_EXIT):
print("\n{}".format(("-" * 80)))
choice = input(prompt)
print("")
cmd = choice_to_cmd(choice)
if (cmd == _CMD_HAIKU):
show_trigrams_haiku(trigrams)
elif (cmd == _CMD_RANDKEY):
show_trigrams_phrase_from_random_key(trigrams)
elif (cmd == _CMD_A2Z):
show_contents_of_trigrams_a2z(trigrams)
else:
continue
print("\nExiting Triagrammatron Demo")
else:
source_pathname = str(source_path)
fmt = "\nMissing text document {} from local source folder."
print(fmt.format(source_pathname))
print("\nRestart script and provide valid document name.\n")
if __name__ == "__main__":
run_trigrammatron_demo_ui()
|
3b94df7d82607cafabe39420fcaca45a812500ee | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/brian_minsk/lesson02/CodingBat/List-1/same_first_last.py | 223 | 3.53125 | 4 | def same_first_last(nums):
if len(nums) > 0 and nums[0] == nums[len(nums) - 1]:
return True
return False
print(same_first_last([1, 1, 3, 1]))
print(same_first_last([0, 1, 3, 1]))
print(same_first_last([5])) |
248c93f7a99d9f78b8c15eca6605d59f7a0644c0 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jason_jenkins/lesson09/mailroom_oo/cli_main.py | 2,466 | 3.75 | 4 | #!/usr/bin/env python3
"""
Lesson 9: Mail Room Part Object Oriented (cli_main)
Course: UW PY210
Author: Jason Jenkins
"""
from donor_models import Donor, DonorCollection
import sys
def send_thanks():
"""
Method used to probt donor name or list out donors
"""
response = ""
while True:
response = input('Input donors name, "list", or "exit": ').lower()
if(response == "exit"):
break
elif response == "list":
print(donors.get_list())
else:
break
if(response != "exit"):
try:
total = float(input('Input amount to donate or "0" to exit: '))
if(total != 0):
print(donors.donate(response, total))
except ValueError:
print("Must input a valid float")
def display_report():
print(f"{'Donor Name':30}|{'Total Given':^16}|", end='')
print(f"{'Num Gifts':^14}|{'Average Gift':^16}")
print(f"{'-'*79}")
for row in donors.get_report():
print(f"{row[0]:30} ${row[1]:15}{row[2]:15} ${row[3]:15}")
def quit_program():
"""
Method used to quit the program
"""
sys.exit()
def startup_prompt():
"""
Prombt user for action they what to take
"""
while True:
print()
print("Do you want to:")
print(' 1 - Send a Thank You to a single donor.')
print(' 2 - Create a Report.')
print(' 3 - Quit.')
response = input("Input numbered option you wish to do: ").strip()
try:
menu_dict[response]()
except KeyError:
print(f"{response} is not a valid input.")
# Global Variables
donors = DonorCollection()
menu_dict = {
"1": send_thanks,
"2": display_report,
"3": quit_program
}
if __name__ == "__main__":
# Initial Setup
will_gates = Donor("William Gates", 1345.462)
mark_zuck = Donor("Mark Zuckerberg", 12546.124)
mark_zuck.give(13445.124)
jeff_bezo = Donor("Jeff Bezos", 1234.123)
jeff_bezo.give(12341431.12)
paul_allen = Donor("Paul Allen", 734.12)
paul_allen.give(124.41)
paul_allen.give(10000)
jason_jenkins = Donor("Jason Jenkins", 10)
jason_jenkins.give(20)
jason_jenkins.give(30)
jason_jenkins.give(40)
jason_jenkins.give(50)
jason_jenkins.give(60)
donors.append(will_gates)
donors.append(mark_zuck)
donors.append(jeff_bezo)
donors.append(paul_allen)
donors.append(jason_jenkins)
startup_prompt()
|
fa130c5f58699714da30bdf148230f263e2c312d | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/cbrown/Lesson 4/students.py | 378 | 3.9375 | 4 | #Reading in students.txt file
fname = 'students.txt'
with open(fname,'r') as f:
languages = set()
for line in f:
line = line.rstrip()
colon_num = line.find(':')
line = line[colon_num + 1:]
line = line.split(',')
for language in line:
if language.islower():
languages.add(language)
print(languages)
|
a08755e25b2cbeaa1fb82dc7bd3ad773da522182 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/steve-long/lesson04-dicts-sets-files/ex-4-1-dict-and-set-lab/dict_lab.py | 5,443 | 4.34375 | 4 | #!/usr/bin/env python3
# =============================================================================
# Python210 | Fall 2020
# -----------------------------------------------------------------------------
# Lesson04
# Dictionary and Set Lab (dict_lab.py)
# Steve Long 2020-10-13 | v0
#
# Requirements:
# =============
#
# Dictionaries [D1]
# -----------------
#
# [D1.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.)
# [D1.2] Display the dictionary.
# [D1.3] Delete the entry for "cake".
# [D1.4] Display the dictionary.
# [D1.5] Add an entry for "fruit" with "Mango" and display the dictionary.
# [D1.6] Display the dictionary keys.
# [D1.7] Display the dictionary values.
# [D1.8] Display whether or not "cake" is a key in the dictionary (i.e.
# False) (now).
# [D1.9] Display whether or not "Mango" is a value in the dictionary (i.e.
# True).
#
# Dictionaries [D2]
# -----------------
#
# [D2.1] Using the dic!onary 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?). The result should look something
# like:
#
# {"name": 0, "city": 2, "cake": 2}
#
# Sets [S1]
# ---------
#
# [S1.1] Create sets s2, s3 and s4 that contain numbers from zero through
# twenty, divisible by 2, 3 and 4 (figure out a way to compute those–
# don't just type them in).
# [S1.2] Display the sets.
# [S1.3] Display if s3 is a subset of s2 (False)
# and if s4 is a subset of s2 (True).
#
# Sets [S2]
# ---------
#
# [S2.1] Create a set with the letters in 'Python' and add 'i' to the set.
# [S2.2] Create a frozenset with the letters in 'marathon'.
# [S2.3] Display the union and intersec!on of the two sets.
#
# Assumptions:
# ============
#
# Minimalist solutions are satisfactory.
#
# Implementation:
# ===============
#
# Function safe_input and demo_safe_input. Checked with flake8.
#
# Dependencies:
# =============
#
# None
#
# Script Usage:
# =============
#
# ./dict_lab.py
#
# Issues:
# =======
#
# None.
#
# History:
# ========
# 000/2020-10-15/sal/Completed.
#
# =============================================================================
def solution_set_d1():
"""
Run solution set D1 (dictionaries).
"""
print("\nSolution Set [D1]")
print("\nSolution [D1.12]")
print("d = dict(name=\"Chris\", city=\"Seattle\", cake=\"Chocolate\")")
d = dict(name="Chris", city="Seattle", cake="Chocolate")
#
print("\nSolution [D1.2]")
print("d = {}".format(d))
#
print("\nSolution [D1.3]")
print("del(d[\"cake\"])")
del(d["cake"])
#
print("\nSolution [D1.4]")
print("d = {}".format(d))
#
print("\nSolution [D1.5]")
print("d[\"fruit\"] = \"Mango\"")
d["fruit"] = "Mango"
#
print("\nSolution [D1.6]")
print("d.keys() = {}".format(d.keys()))
#
print("\nSolution [D1.7]")
print("d.values() = {}".format(d.values()))
#
print("\nSolution [D1.8]")
key = "cake"
found = (key in d)
print("\"{}\" in d => {}".format(key, found))
#
print("\nSolution [D1.9]")
value = "Mango"
found = (value in d.values())
print("\"{}\" in d.values() => {}".format(value, found))
def solution_set_d2():
"""
"""
print("\nSolution Set [D2]")
print("\nSolution [D2.1]")
def t_count(s):
return s.lower().count("t")
print("d = dict(name=t_count(\"Chris\"),"
" city=t_count(\"Seattle\"), cake=t_count(\"Chocolate\"))")
d = dict(name=t_count("Chris"),
city=t_count("Seattle"),
cake=t_count("Chocolate"))
print("d = {}".format(d))
def solution_set_s1():
"""
"""
print("\nSolution Set [S1]")
print("\nSolution [S1.1]\n(no output)")
s234 = [[[], 2], [[], 3], [[], 4]]
for j in range(0, 3):
s = s234[j][0]
n = s234[j][1]
for i in range(0, 21):
if ((i % n) == 0):
s.append(i)
s234[j][0] = set(s)
set2 = s234[0][0]
set3 = s234[1][0]
set4 = s234[2][0]
print("\nSolution [S1.2]")
print("set2 = {}".format(set2))
print("set3 = {}".format(set3))
print("set4 = {}".format(set4))
print("\nSolution [S1.3]")
print("set3.issubset(set2) = {}".format(set3.issubset(set2)))
print("set4.issubset(set2) = {}".format(set4.issubset(set2)))
def solution_set_s2():
"""
"""
print("\nSolution Set [S2]")
print("\nSolution [S2.1]")
print("set1 = set(list(\"Python\"))")
set1 = set(list("Python"))
print("set1 = {}".format(set1))
print("set1.add(\"i\")")
set1.add("i")
print("set1 = {}".format(set1))
print("\nSolution [S2.2]")
print("set2 = frozenset(set(list(\"marathon\")))")
set2 = frozenset(set(list("marathon")))
print("set2 = {}".format(set2))
print("\nSolution [S2.3]")
u_set1_set2 = set1.union(set2)
print("set1.union(set2) = {}".format(u_set1_set2))
i_set1_set2 = set1.intersection(set2)
print("set1.intersection(set2) = {}".format(i_set1_set2))
def main():
"""
"""
solution_set_d1()
solution_set_d2()
solution_set_s1()
solution_set_s2()
if __name__ == "__main__":
main()
|
01e6e518fe93f0e2b8df5b26d563fd39960de252 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/pkoleyni/lesson04/trigram.py | 1,811 | 4.21875 | 4 | #!/usr/bin/env python3
import sys
import random
def make_list_of_words(line):
"""
This function remove punctuations from a string using translate()
Then split that string and return a list of words
:param line: is a string of big text
:return: List of words
"""
replace_reference = {ord('-'): ' ', ord(','): '', ord(','): '', ord('.'): '', ord(')'): '', ord('('): '', ord ('"'): ''}
line = line.translate(replace_reference)
words = line.split()
return words
def read_file (file_name):
big_line = []
with open(file_name, 'r') as f:
for line in f:
big_line.append(line)
return big_line
def build_trigrams(words):
"""
Buit a trigram dictionary
:param words:
:return:
"""
word_pairs = dict()
for i in range(len(words) - 2):
pair = tuple(words[i:i + 2])
follower = words[i + 2]
if pair not in word_pairs:
word_pairs[pair] = [follower]
else:
word_pairs[pair].append(follower)
return word_pairs
def new_text(trigrams_dic):
a_list = []
l = len(trigrams_dic.keys())
for i in range(10):
random_number = random.randint(0,l)
key = list(trigrams_dic.keys())[random_number]
a_list.append(" ".join(list(key)))
a_list.append(" ".join(trigrams_dic[key]))
return (" ".join(a_list))
if __name__ == "__main__":
try:
filename = sys.argv[1]
except IndexError:
print("You must pass in a filename")
sys.exit(1)
file_content = read_file (filename)
list_of_words = make_list_of_words(" ".join(file_content))
# list_of_words = make_list_of_words(" ".join(read_file('sherlock_small.txt.py')))
trigrams = build_trigrams(list_of_words)
print(new_text(trigrams))
|
fc8f87370cb6417db76de0cc7695ebedf0a9f5d2 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/cbrown/Lesson 6/mailroom_part_four.py | 5,382 | 3.953125 | 4 | #!/usr/bin/env python3
# Mailroom Part 4
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 - Send Letters to All Donors",
"4 - Quit",
" "))
def donor_verify(donor_name, amount, donor_list):
# Donor name found in list. Add amount to entry.
if donor_name in donor_list:
donors[donor_name].append(amount)
print('\n')
# not found in list. Add new donor entry
else:
new_entry = []
new_entry.append(amount)
donors[donor_name] = new_entry
return donors
def thank_you_note(donor_name, amount):
thanks_dict = {'donor_name': donor_name, 'amount': amount}
# Formatted Thank You Note
message = ('Dear {donor_name}, \n\nThank you for your show of support and generosity. '
'Your Donation of ${amount} will contribute to saving Olympic Marmots '
'in Washington State. These Marmota are special and a unique gift to the Olympic '
'National Park ecosystem. As a way of saying thank you. '
'You will be receiving your very own Olympic Marmot t-shirt in the mail!\n\n'
'Sincerely,\n\nThe Olympic Marmot Wildlife Foundation\n').format(**thanks_dict)
return message
def send_thanks():
print('\n', "For A Complete Donor List Type 'List'\n ")
# Create a unique list of donor names
donor_list = [names for names in donors.keys()]
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
try:
amount = float(input("How Much Did This Person Donate?\n "))
except ValueError: #start prompt over again if exception occurs
print('Please input the amount donated')
send_thanks()
# updates donor database by checking existing donors and adding new ones if they don't exist
donor_verify(donor_name, amount, donor_list)
# formats message thanking the individual donor
message = thank_you_note(donor_name, amount)
print(message)
# function for sorting key
def sum_value(donations):
item = donations[1]
return sum(item)
def report_rows(name, amounts):
total_given = sum(amounts)
num_gift = len(amounts)
avg_gift = total_given/num_gift
total_given = '{:,.0f}'.format(total_given)
avg_gift = '{:,.0f}'.format(avg_gift)
row = '{:<25}${:^15}{:^15}${:^15}'.format(name, total_given, num_gift, avg_gift)
return row
def print_report(report_lines):
'''
Prints the output of the donor report using data generated from report_rows function & report_lines list
'''
# prints the header of the 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)
# prints name, total, num of gifts, and avg gift
for row in report_lines:
print(row)
def create_report():
'''
Creates the data used in donor reports
'''
# create a sorted donations dict by total amount
sorted_donations = sorted(donors.items(), key = sum_value, reverse=True)
report_lines = []
for k, v in sorted_donations:
report_lines.append(report_rows(k, v))
print_report(report_lines)
def write_file(name, message):
'''
Creates a text file of each thank you message for each donor
'''
fname = name + '.txt'
with open(fname, 'w') as f:
f.write(message)
def create_message(name, amount):
'''
Creates a personalized & formatted message for each donor
'''
tmt_amount = sum(amount)
message = ('Dear {}, \n\nThank you for your show of support and generosity. '
'Your donations of ${:,.1f} will contribute to saving Olympic Marmots '
'in Washington State. These Marmota are special and a unique gift to the Olympic '
'National Park ecosystem. As a way of saying thank you. '
'You will be receiving your very own Olympic Marmot t-shirt in the mail!\n\n'
'Sincerely,\n\nThe Olympic Marmot Wildlife Foundation\n').format(name, tmt_amount)
return message
def send_letters():
'''
creates and writes a letter to each donor in the donor database
'''
for name, amount in donors.items():
message = create_message(name, amount)
write_file(name, message)
def exit_from():
print('Work Completed. Good Bye!')
sys.exit()
response_dict = {"1": send_thanks, "2": create_report, "3": send_letters, "4": exit_from}
def main():
while True:
try:
response = input(prompt)
response_dict.get(response)()
except TypeError:
print('The choice you have selected is not an option. Please select from the menu.')
continue
if __name__ == "__main__":
main()
|
abfaf78910cf739ebcc1e3a3d9ed8b5945672bb1 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/joli-u/lesson04/dict_lab.py | 2,312 | 4.4375 | 4 | #!/usr/bin/env python
"""
dictionaries 1
"""
print("-----DICTIONARIES 2-----\n")
# create dictionary
_dict = {'name': 'Chris',
'city': 'Seattle',
'cake': 'Chocolate'}
_dict1 = _dict.copy()
# display dictionary
print("display dictionary: {}".format(_dict1))
# delete the "cake" entry
_dict1.pop('cake')
# display the dictionary
print("delete cake entry: {}".format(_dict1))
# add "fruit entry"
_dict1['fruit'] = 'Mango'
# display the dictionary
print("add fruit:mango entry: {}".format(_dict1))
# display the dictionary keys; values
print(_dict1.keys())
print(_dict1.values())
# determine whether 'cake' and 'Mango' is in the dictionary
print("is cake a key?: ", end="")
print('cake' in _dict1.keys())
print("is mango a value?: ", end="")
print('Mango' in _dict1.values())
"""
dictionaries 2
"""
print("\n\n-----DICTIONARIES 2-----\n")
_dict2 = {}
# make dictionary with keys from _dict except with the values being number of t's in original
for k,v in _dict.items():
_key = k
_value = (v.lower()).count('t')
_dict2[_key] = _value
print("display dictionary: {}".format(_dict2))
"""
sets 1
"""
print("\n\n-----SETS 1-----\n")
# create inital set with numbers from 0 to 20
s1 = set(range(21))
# create sets that contain numbers that are divisible by 2,3,4
s2 = set()
s3 = set()
s4 = set()
for item in s1:
if (item%2) == 0:
s2.update([item])
if (item%3) == 0:
s3.update([item])
if (item%4) == 0:
s4.update([item])
# display the sets
print("s1={}\ns2={}\ns3={}\ns4={}".format(s1,s2,s3,s4))
# display if s() is a subset of s2
print("is s3 a subset of s2?: ",end='')
print(s3.issubset(s2))
print("is s4 a subset of s2?: ",end='')
print(s4.issubset(s2))
"""
sets 2
"""
print("\n\n-----SETS 2-----\n")
# create set with letters in 'python'
_set2 = set()
_str1 = []
_str1.extend('python')
_set2.update(_str1)
print("set={}".format(_set2))
# add 'i' to the set
_set2.update('i')
print("set={}".format(_set2))
# create frozen set with letters in 'marathon'
_str2 = []
_str2.extend('marathon')
_fset = frozenset(_str2)
print(_fset)
# display the union and intersection of the two sets
_union = _set2.union(_fset)
print("union={}".format(_union))
_intsct = _set2.intersection(_fset)
print("intersection={}".format(_intsct)) |
565b617a8b5c9d9fd86bc346abee60266b04092d | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/thecthaeh/Lesson08/circle_class.py | 2,228 | 4.46875 | 4 | #!/usr/bin/env python3
import math
import functools
""" A circle class that can be queried for its:
radius
diameter
area
You can also print the circle, add 2 circles together, compare the size of 2 circles (which is bigger
or are they equal), and list and sort circles.
"""
@functools.total_ordering
class Circle:
radius = 0
def __init__(self, radius):
self.radius = radius
@property
def diameter(self):
_diameter = self.radius * 2
return _diameter
@diameter.setter
def diameter(self, value):
self._diameter = value
self.radius = round((self._diameter / 2), 2)
@property
def area(self):
_area = (math.pi * (math.pow(self.radius, 2)))
return round(_area, 2)
@classmethod
def from_diameter(cls, diam_value):
cls.diameter = diam_value
cls.radius = round((cls.diameter / 2), 2)
return cls
def __str__(self):
return f"Circle with radius: {self.radius}"
def __repr__(self):
return f"Circle({self.radius})"
def __add__(self, other):
"""
add two circle objects together
"""
new_radius = self.radius + other.radius
return Circle(new_radius)
def __mul__(self, other):
"""
multiply a circle object by a number
"""
return Circle(self.radius * other)
def __rmul__(self, other):
return self.__mul__(other)
def __eq__(self, other):
return self.radius == other.radius
def __lt__(self, other):
return self.radius < other.radius
def sort_key(self):
return self.radius
class Sphere(Circle):
def __str__(self):
return f"Sphere with radius: {self.radius}"
def __repr__(self):
return f"Sphere({self.radius})"
@property
def volume(self):
_volume = ((4/3) * math.pi * (math.pow(self.radius, 3)))
return round(_volume, 2)
@property
def area(self):
"""
Calculate the surface area of a sphere
"""
_area = (4 * math.pi * (math.pow(self.radius, 2)))
return round(_area, 2) |
4d73c1447d9ec48e3ea9cb14fe30db9b890d7386 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Shweta/Lesson08/circle.py | 1,505 | 4.3125 | 4 | #!/usr/bin/env python
#circel program assignment for lesson08
import math
class Circle(object):
def __init__(self,radius):
self.radius=radius
# self._radius=radius
@classmethod
def from_diameter(cls,_diameter):
#self=cls()
radius = _diameter/ 2
return cls(radius)
@property
def diameter(self):
#self.diameter=self.radius*2
diameter=self.radius*2
return diameter
@diameter.setter
def diameter(self,value):
self.radius = value / 2
#return value
@property
def area(self):
area=(self.radius ** 2)*math.pi
return area
def __str__(self):
return "Circle with radius:" + str(self.radius)
def __repr__(self):
return f"'{self.__class__.__name__}({self.radius})'"
def __add__(self,other):
return Circle(self.radius + other.radius)
def __mul__(self,other):
return Circle(self.radius * other)
def __lt__(self,other):
return (self.radius < other.radius)
def __eq__(self,other):
return(self.radius == other.radius)
class Sphere(Circle):
def __str__(self):
return "Sphere radius {} and diameter is {}".format(self.radius,self.diameter)
def __repr__(self):
return "Sphere()".format(self.radius)
@property
def area(self):
return (self.radius ** 2) * math.pi * 4
@property
def volume(self):
return (self.radius ** 3) *math.pi * (4/3)
|
26de213de70ad3bff7a84c63a9d4a5b31c11f25a | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/rod_musser/lesson03/mailroom.py | 2,686 | 3.921875 | 4 | #!/usr/bin/env python3
import sys
donors = [
['Carmelo Anthony', 1, 50],
['Damien Lillard', 100.50, 99, 10000],
['CJ McCollum', 24000, 70, 100, 5, 300],
['Hassan Whiteside', 10000],
['Terry Stotts', 500, 500, 100, 100, 100],
]
welcome_prompt = "\n".join(("Welcome to the Local Charity Mail Room System",
"Please choose from the following options:",
"1 - Send a Thank You",
"2 - Create a Report",
"3 - Quit",
">>> "))
def main():
while True:
response = input(welcome_prompt)
if response == "1":
send_thank_you()
elif response == "2":
create_report()
elif response == "3":
exit_program()
else:
print("Not a valid option!")
def list_donors():
newLine = '\n'
print(f"{newLine.join(x[0] for x in donors)}")
def send_thank_you():
response = input("Please enter a full name: ")
if response.lower() == "list":
list_donors()
send_thank_you()
else:
amount = input("Please enter the donation amount: ")
add_donation(find_donor(response), amount)
def find_donor(name):
"""
Returns a list containing the name of the donor
and a history of their donations.
If the name cannot be found, crates a new list
for the new donor
"""
for d in donors:
if name in d:
return d
new_donor = [name, ]
donors.append(new_donor)
return new_donor
def add_donation(donor, amt):
"""
Records a donation and prints a thank you email.
Expects a list which contains a donor and a list of amounts.
"""
amt = float(amt)
donor.append(amt)
print(f"Thank you {donor[0]} for you generous donation of ${amt:.2f}")
def sort_key(donor_summary):
return donor_summary[1]
def create_report():
report = []
for d in donors:
total_amount = sum(d[1:])
number_of_gifts = len(d) - 1
average_gift = round(total_amount / number_of_gifts, 2)
donor_summary = [d[0], total_amount, number_of_gifts, average_gift]
report.append(donor_summary)
print_report(sorted(report, key=sort_key, reverse=True))
def print_report(report):
print("Donor Name" + (' ' * 16) + ("| Total Given | Num Gifts | Avergage Gift"))
print("-" * 68)
row = "{name:<26s} ${total:=12.2f} {num:10d} ${avg:14.2f}".format
for donor in report:
print(row(name=donor[0], total=donor[1], num=donor[2], avg=donor[3]))
def exit_program():
print("You made a difference today. Have a good one!")
sys.exit()
if __name__ == "__main__":
main()
|
8b7b1831a6a0649a23ba3028d1c3fec8f93528b6 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/will_chang/lesson04/dict_lab.py | 2,145 | 4.15625 | 4 | # Dictionaries 1
print("Dictionaries 1\n--------------\n")
dict_1 = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
print(dict_1)
print("\nThe entry for cake was removed from the dictionary.")
dict_1.pop('cake')
print(dict_1)
print("\nAn entry for fruit was added to the dictionary.")
dict_1['fruit'] = 'Mango'
print("\nHere are the dictionary's current keys:")
print(dict_1.keys())
print("\nHere are the dictionary's current values:")
print(dict_1.values())
print("\nCheck if 'cake' is a key in the dictionary: {}".format('cake' in dict_1.keys()))
print("\nCheck if 'Mango' is a value in the dictionary: {}".format('Mango' in dict_1.values()))
# Dictionaries 2
print("\n\nDictionaries 2\n--------------\n")
print("Here's the dictionary from Dictionaries 1:")
print(dict_1)
dict_2 = dict_1.copy()
for key in dict_2:
dict_2[key] = dict_2[key].lower().count('t')
print("\nThis is a new dictionary with the same keys from dictionary 1 but with the number of 't's in each value as the corresponding dictionary 1 value:")
print(dict_2)
# Sets 1
print("\n\nSets 1\n------\n")
s2 = set(range(0, 21, 2))
s3 = set(range(0, 21, 3))
s4 = set(range(0, 21, 4))
print("Here is a set s2 containing numbers from 0 - 20 that are divisble by 2:\n{}".format(s2))
print("\nHere is a set s3 containing numbers from 0 - 20 that are divisble by 3:\n{}".format(s3))
print("\nHere is a set s4 containing numbers from 0 - 20 that are divisble by 4:\n{}".format(s4))
print("\nCheck if s3 is a subset of s2: {}".format(s3.issubset(s2)))
print("\nCheck if s4 is a subset of s2: {}".format(s4.issubset(s2)))
# Sets 1
print("\n\nSets 2\n------\n")
s_python = set(['P','y','t','h','o','n'])
s_python.add('i')
print("This is a set with the letters in 'Python' with 'i' added:\n{}".format(s_python))
fs_marathon = frozenset(['m', 'a', 'r', 't', 'h', 'o', 'n'])
print("\nThis is a frozenset with the letters in 'marathon':\n{}".format(fs_marathon))
print("\nThis is the union of the set and frozenset:\n{}".format(s_python.union(fs_marathon)))
print("\nThis is the intersection of the set and frozenset:\n{}".format(s_python.intersection(fs_marathon))) |
45cff042a51e4bd53ab45c01e1ef95da879ba1e9 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mark_mcduffie/lesson2/codingbat.py | 616 | 3.671875 | 4 |
#Logic2
def make_bricks(small, big, goal):
if (goal%5)<=small and (goal-(big*5))<=small:
return True
else:
return False
def lone_sum(a, b, c):
if (a != b and b != c and a != c):
return a + b + c
elif(a == c and b != a):
return b
elif(a == b and a != c):
return c
elif(b == c and a != b):
return a
else:
return 0
#List2
def count_evens(nums):
count = 0
for n in nums:
if(n%2 == 0):
count = count + 1
return count
def big_diff(nums):
return max(nums) - min(nums)
def centered_average(nums):
nums.sort()
return sum(nums[1:-1]) / (len(nums) - 2)
|
29576ffa5771ba649da5a33f9338e4a794ee56d2 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Devon_Peterka/Lesson_3/slicing_lab.py | 2,171 | 3.96875 | 4 | #!/usr/bin/env python3
'''
# Create functions to take a sequence and create a copy except:
# 1) with the first and last items exchanged
# 2) with every other term removed
# 3) with the first and last (4) terms removed
# 4) with reversed elements
# 5) with last 1/3, then first 1/3, then middle 1/3 in the new order
'''
# first and last terms swapped.
def first_last(seq):
return seq[-1:] + seq[1:-1] + seq[:1]
# with every other term removed.
def every_other(seq):
return seq[::2]
# with first and last (4) removed.
def no_firstlast_four(seq):
return seq[4:-4]
# with elements reversed.
def reverse_it_all(seq):
return seq[::-1]
# with last 1/3, first 1/3, then middle
# last, then first, then middle == last 1/3 first, then the remainder in original order
def swap_thirds(seq): #seq is odd length, bias to the last 1/3 sequence
return seq[-len(seq)//3:] + seq[:-len(seq)//3]
#Test out the functions
if __name__ == '__main__':
#Test Them Out:
seq = "this is a string"
assert first_last(seq) == 'ghis is a strint'
assert every_other(seq) == 'ti sasrn'
assert no_firstlast_four(seq) == ' is a st'
assert reverse_it_all(seq) == 'gnirts a si siht'
assert swap_thirds(seq) == 'stringthis is a '
print('Tested Sequence =', seq)
#and test again with a tuple
seq = (2, 54, 13, 12, 5, 32)
assert first_last(seq) == (32, 54, 13, 12, 5, 2)
assert every_other(seq) == (2, 13, 5)
assert no_firstlast_four(seq) == ()
assert reverse_it_all(seq) == (32, 5, 12, 13, 54, 2)
assert swap_thirds(seq) == (5, 32, 2, 54, 13, 12)
print('Tested Sequence =', seq)
#and test one final time with a longer list
seq = [1, 4, 'a', 'bob', 32, 'yahoo', 12.3, 1, 2, 3, 4]
assert first_last(seq) == [4, 4, 'a', 'bob', 32, 'yahoo', 12.3, 1, 2, 3, 1]
assert every_other(seq) == [1, 'a', 32, 12.3, 2, 4]
assert no_firstlast_four(seq) == [32, 'yahoo', 12.3]
assert reverse_it_all(seq) == [4, 3, 2, 1, 12.3, 'yahoo', 32, 'bob', 'a', 4, 1]
assert swap_thirds(seq) == [1, 2, 3, 4, 1, 4, 'a', 'bob', 32, 'yahoo', 12.3]
print('Tested Sequence =', seq)
print('\nAll Tests Passed\n')
|
57d92674b6e105e799e4927ea8d83742fa2e5341 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jbutts/Lesson03/list_lab.py | 5,820 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Module 3: 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).
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.
'''
def show_list(prompt, items):
# Print a comma-separated list of the items in a list
display = prompt + ": " + ", ".join(len(items) * ["{}"]).format(*items)
print(display)
def enumerate_list(items):
# Print a numbered list
for i, items in enumerate(items):
print("{:<4}{:<10}".format(i + 1, items))
def remove_list_item_by_name(item, items):
# Remove an item from a list if it matches user input
while item in items:
items.remove(item)
if item not in items:
break
else:
remove_item = int(input("\nplease choose the number of the fruit you'd like to delete (1 - " + str(len(items)) + ") >>> "))
return items
print("\n\nSERIES 1\n\n")
FRUITS = ['Apples', 'Pears', 'Oranges', 'Peaches']
FRUITS_ORIG = list(FRUITS) # so we a copy instead of a pointer!!!
show_list("Initial list", FRUITS)
ADD_FRUIT = str(input("Please input another fruit to add to the list >> "))
FRUITS.append(ADD_FRUIT)
show_list("Added item to end", FRUITS)
SHOW_NUMBER = int(input("Please input the number of the fruit you'd like to display"
" (1-" + str(len(FRUITS)) + ")>> "))
SHOW_NUMBER -= 1 # Add number so our numbering starts at 1
print("Selection: " + FRUITS[SHOW_NUMBER])
# add to beginning using +
FRUITS = ['Banana'] + FRUITS
show_list("Added Banana to front of list using +", FRUITS)
# add to beginning using append
FRUITS.insert(0, 'Pineapple')
show_list("Added Pineapple to front using insert", FRUITS)
'''
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("\n\nSERIES 2\n\n")
FRUITS = ['Apples', 'Pears', 'Oranges', 'Peaches']
# Show the list created in Series 1
show_list("List created in Series 1", FRUITS)
# Remove last fruit from list
FRUITS.pop(len(FRUITS) - 1)
show_list("Removed last item", FRUITS)
# List available items for deletion:
print("\n\nLet's delete one of these fruits:\n")
enumerate_list(FRUITS)
REMOVE_ITEM = int(input("\nplease choose the number of the fruit you'd like to delete"
" (1 - " + str(len(FRUITS)) + ") >>> "))
FRUITS.pop(REMOVE_ITEM)
FRUITS = FRUITS * 2
print("\n\nBONUS!: Let's delete all of one type of these fruits:\n")
enumerate_list(FRUITS)
REMOVE_ITEM = int(input("\nplease choose the number of the fruit you'd like to delete"
" (1 - " + str(len(FRUITS)) + ") >>> "))
REMOVE_FRUIT = FRUITS[REMOVE_ITEM - 1] # Handle the off-by-1
FRUITS = remove_list_item_by_name(REMOVE_FRUIT, FRUITS)
print("\n\nUpdated list after deletion: \n")
enumerate_list(FRUITS)
'''
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.
'''
print("\n\nSERIES 3\n\n")
FRUITS = ['Apples', 'Pears', 'Oranges', 'Peaches']
print("\n\nLet's remove items from the list that you don't like...\n\n")
enumerate_list(FRUITS)
remove_fruits = []
for fruit in FRUITS:
response = '' # declare or reset answer from previous
while response.lower() not in ["yes", "no"]:
response = str(input("Do you like {}?".format(fruit) + " (yes/no) >>> ")).lower()
if response == 'no':
remove_fruits.append(fruit) # Actually removing the fruit from the list here causes an
# off-by-one. Create a list and do it after this loop.
remove_fruits.append(fruit) # Actually removing the fruit from the list here causes an off-by-one. Create a list and do it after this loop.
FRUITS = remove_list_item_by_name(fruit, FRUITS)
print("\n\nHere are the fruits you like: \n")
enumerate_list(FRUITS)
'''
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("\n\nSERIES 4\n\n")
FRUITS = ['Apples', 'Pears', 'Oranges', 'Peaches']
FRUITS_ORIG = FRUITS[:]
FRUITS_COPY = FRUITS[:]
print("\n\nA:\n\n")
STIURF = [] # fruits spelled backwards!
for fruit in FRUITS:
STIURF.append(fruit[::-1].lower().title())
show_list("Here's the fruits before", FRUITS)
FRUITS = STIURF
show_list("Here's the same fruits spelled backwards", FRUITS)
print("\n\nB:\n\n")
FRUITS_ORIG.pop(len(FRUITS_ORIG) - 1)
show_list("here's the original list with the last item removed", FRUITS_ORIG)
show_list("here's a copy the original list", FRUITS_COPY)
|
599d561eff3a2e002285baa0b662abc294d5aa73 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/tommy_bennett/lesson2/fizz_buzz.py | 223 | 3.609375 | 4 | for i in range(100):
x = i + 1
fizz_buzz = ''
if x % 3 == 0:
fizz_buzz = "Fizz"
if x % 5 == 0:
fizz_buzz += "Buzz"
if len(fizz_buzz):
print(fizz_buzz)
else:
print(x)
|
55f48aff0bc258783bf6e1cf91b4668bf5e7b3de | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/scott_bromley/lesson03/strformat_lab.py | 2,725 | 4.40625 | 4 | #!/usr/bin/env python3
# string formatting exercises
def main():
print(task_one())
print(task_two())
print(formatter((2, 3, 5, 7, 9))) #task three
print(task_four())
task_five()
task_six()
def task_one(file_tuple=None):
'''
given a tuple, produce a specific string using string formatting
:return: formatted string
'''
if file_tuple is None:
file_tuple = (2, 123.4567, 10000, 12345.67)
return "file_{:03d} : {:.2f}, {:.2e}, {:.2e}".format(file_tuple[0], file_tuple[1], file_tuple[2], file_tuple[3])
def task_two(file_tuple=None):
'''
given a tuple, produce a specific string using string formatting
:return: f-string
'''
if file_tuple is None:
file_tuple = (2, 123.4567, 10000, 12345.67)
return f"file_{file_tuple[0]:03} : {file_tuple[1]:{8}.{5}}, {file_tuple[2]:.2e}, {file_tuple[3]:.2e}"
def formatter(in_tuple):
'''
dynamically build format string to reflect tuple size in output
:return: formatted string
'''
l = len(in_tuple)
# return ("the {} numbers are: " + ", ".join(["{}"] * l)).format(l, *in_tuple)
return f"the {l} numbers are: {', '.join(str(num) for num in in_tuple)}"
def task_four(file_tuple=None):
'''
use index numbers from tuple to specify positions in print formatting
:return: f-string
'''
if file_tuple is None:
file_tuple = (4, 30, 2017, 2, 27)
return f"{file_tuple[3]:02} {file_tuple[4]} {file_tuple[2]} {file_tuple[0]:02} {file_tuple[1]}"
def task_five():
'''
create f-string that displays "The weight of an orange is 1.3 and the weight of a lemon is 1.1" from a provided list
:return: None
'''
fruit_weight = ['oranges', 1.3, 'lemons', 1.1]
print(f"The weight of an {fruit_weight[0][:-1]} is {fruit_weight[1]} and the weight of a {fruit_weight[2][:-1]} is {fruit_weight[3]}")
print(f"The weight of an {fruit_weight[0][:-1].upper()} is {fruit_weight[1] * 1.2} and the weight of a {fruit_weight[2][:-1].upper()} is {fruit_weight[3] * 1.2}")
return None
def task_six():
'''
print a table of several rows, each with a name, an age and a cost
:return: None
'''
scotch = ["Glenmorangie", "Balvenie Single Malt", "Macallan Lalique", "Glenfiddich", "Ardbeg"]
ages = ["18 years", "50 years", "62 years", "30 years", "10 years"]
price = ["$130.00", "$50,000.00", "$47,285.00", "$799.00", "$90.00"]
print(f"SCOTCH:{'':<30}AGE:{'':<20}PRICE:{'':>20}")
for scotch, age, price in zip(scotch, ages, price):
print(f"{scotch:<30}{age:^20}{price:>17}")
return None
if __name__ == "__main__":
print("Running", __file__)
main()
else:
print("Running %s as imported module", __file__) |
504005dfe16fe1e63004415fa3c65e9026160484 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/tim_lurvey/lesson09/mailroom_oo/cli_main.py | 5,251 | 3.59375 | 4 | #!/usr/bin/env python
__author__ = 'Tim Lurvey, ig408c'
import sys
import os
from donor_classes import DonorRepository
my_data_repo = DonorRepository()
my_data_repo.add_new_donor(('Tom Hanks', 24536.20, 3))
my_data_repo.add_new_donor(('Barry Larkin', 4521., 3))
my_data_repo.add_new_donor(('Mo Sizlack', 88.88, 2))
my_data_repo.add_new_donor(('Anonymous', 100., 1))
my_data_repo.add_new_donor(('Donnald Trump', 1., 3))
def print_formatted_name_list():
print(my_data_repo.formatted_name_list)
return True
def add_new_donor():
"""Add a new donor, from user input"""
# get params
name = input("Name:\n>>>")
while True:
try:
total = input("Total (optional, default is $0):\n>>>$")
float(total)
break
except:
print("'{}' is not numeric. Please input only numbers")
count = 0
# if total, must have count
if total:
while True:
try:
count = input("Number of donations:\n>>>")
int(count)
break
except:
print("'{}' is not numeric. Please input only numbers")
# add them
my_data_repo.add_new_donor((name, total, count))
donor = my_data_repo.get_donor(name=name)
print("Added: {0}, Total: ${1}, Count: {2}".format(donor.name, donor.total, donor.count))
return True
def get_name_from_user():
"""get name from input"""
name = input("Please enter a full name (Case Sensitive)\n>>>")
if name not in my_data_repo.name_list:
print("name='{}' not in data set. Please add the user at the main menu.".format(name))
name = ""
return name
def get_additional_donation_from_user(name: str):
"""get new donation, if any"""
while True:
additional = input(f"If {name} is making new donation, enter the amount. (0 for no new donation)\n>>>")
try:
float(additional)
break
except ValueError:
print("Invalid numeric amount, please try again.")
return float(additional)
def print_thank_you_donor():
"""print the string 'Thank you' message for a user selected donor"""
name = get_name_from_user()
if not name:
return True
additional = get_additional_donation_from_user(name=name)
#
print(my_data_repo.get_thank_you_email(donor=name, new_donation=float(additional)))
return True
def all_donors_report():
print(my_data_repo.report())
return True
def get_path_from_user():
"""get the path from the user, or return to the previous menu"""
while True:
write_path = input("Enter a path to write letters to. 'q' to return to previous menu\n>>> ").strip()
if write_path == 'q':
# if quitting, unset the variable to return a False boolean test on return
write_path = ""
break
elif os.path.exists(write_path):
# write_path is good, boss! return it
break
else:
print("Cannot access '{}'".format(write_path))
#
return write_path
def write_letter_to_path(name: str, message: str, pathx: str):
with open(os.path.join(pathx, "thank_you_{}.txt".format(name).replace(" ", "_")), "w") as W:
W.write(message)
def write_thank_you_letters_to_path():
wpath = get_path_from_user()
for name in my_data_repo.name_list:
write_letter_to_path(name=name,
message=my_data_repo.get_thank_you_email(donor=name),
pathx=wpath)
return True
def quit_program():
"""Exit the application by unseating the switch"""
exit("\nGoodbye! Exiting program...")
def error(inp: str = ""):
"""Report an error"""
print("\nError on input. Invalid selection \"{}\"".format(inp))
return True
def main():
"""This is the controlling logic for the program. The main loop will
repeat forever until the user specifies to quit.
-- LOGIC FLOW --
1 print_name_list
2 add_new_donor
3 send_thank_you
additional_donation ?
print thank you message
4 print_donor_report
5 write_letters
get_path
write_files
q quit
"""
while True:
# Define main input
msg = "1 : See a list of donor names\n" \
"2 : Add new donor\n" \
"3 : Print a Thank You to individual donor\n" \
"4 : Create Report of all donors\n" \
"5 : Write Thank you letters to all donors\n" \
"q : quit\n>>> "
# Query
request = input("Select:\n{}".format(msg)).strip()
# Error check
if len(request) > 1:
print("\nplease input only '1' or '2' or 'q'\n")
# keep looping until valid result
continue
# Define the logic
logic_dict = {'1': print_formatted_name_list,
'2': add_new_donor,
'3': print_thank_you_donor,
'4': all_donors_report,
'5': write_thank_you_letters_to_path,
'q': quit_program}
# Get the corresponding function and execute it
logic_dict.get(request, error)()
if __name__ == '__main__':
main()
|
3ce552c36077599974fada702350f2e1cae0fc14 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mattcasari/lesson08/assignments/circle_class.py | 2,916 | 4.46875 | 4 | #!/usr/bin/env python3
""" Lesson 8, Excercise 1
@author: Matt Casari
Link: https://uwpce-pythoncert.github.io/PythonCertDevel/exercises/circle_class.html
Description:
Creating circle class and a sphere sub-class
"""
import math
class Circle(object):
# @classmethod
def __init__(self, the_radius=0):
self.radius = the_radius
@classmethod
def from_diameter(cls, diameter):
return cls(diameter/2.0)
@property
def radius(self):
return self._radius
@radius.setter
def radius(self,radius):
self._radius = radius
@property
def diameter(self):
return self._radius *2.0
@diameter.setter
def diameter(self,diameter):
self._radius = diameter/2.0
@property
def area(self):
return self._radius*2.0*math.pi
def __str__(self):
return f"Circle with radius: {self.radius:.6f}"
def __repr__(self):
return f"Circle({self.radius})"
def __add__(self, other):
return Circle(self.radius + other.radius)
def __mul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError("Invalid operator")
def __rmul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError("Invalid operator")
def __gt__(self, other):
return self.radius > other.radius
def __lt__(self, other):
return self.radius < other.radius
def __eq__(self, other):
if isinstance(other, int):
return self.radius == other
elif isinstance(other, Circle):
return self.radius == other.radius
else:
raise TypeError("Invalid Operator")
def __iadd__(self, other):
if isinstance(other, int):
self.radius = self.radius + other
elif isinstance(other, Circle):
self.radius = self.radius + other.radius
else:
raise TypeError("Invalid Operator")
return self.radius
def __imult__(self, other):
if isinstance(other, int):
self.radius = self.radius * other
elif isinstance(other, Circle):
self.radius = self.radius * other.radius
else:
raise TypeError("Invalid Operator")
return self.radius
class Sphere(Circle):
@property
def area(self):
raise NotImplementedError
@property
def volume(self):
return 4/3 * math.pi * (self.radius**3)
def __str__(self):
return f"Sphere with radius: {self.radius}"
def __repr__(self):
return f"Sphere({self.radius})"
|
dd741d197fe93a011b4d73fda67f250e72ef7f28 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/becky_larson/lesson05/Mailroom_Part3.py | 7,068 | 3.703125 | 4 | #!/usr/bin/env python """
import sys
import tempfile
import os
from datetime import date
today = date.today()
"""Mailroom Part 3"""
""" Updates from Part 2
1. Add exception handling
2. Add comprehension
"""
# Prompt user to choose from menu of 4 actions:
# Send a Thank You, Create a Report, Send thanks to all donors or quit.
donor_db = {"Cher": [1000.00, 245.00],
"Drew Barrymore": [25000.00],
"Charlie Brown": [25.00, 50.01, 100.00],
"Jack Black": [256.00, 752.50, 10101.00],
"Sam Smith": [5500.00, 24.00],
}
default_folder = "thank_you_cards"
def sort_key(donors):
# sort by total donations
return sum(donors[1])
def print_name(donor):
print(f'\t{donor}')
return
def list_donors(donors):
print(f'\nNumber of Donors found: {len(donors)}\n\n')
'''
Note: revised code to use comprehension in Mailroom Part 3
Keeping commented code
for donor, donations in donors.items():
print(f'\t{donor}')
'''
[print(f'\t{donor}') for donor, donations in donors.items()]
print('\n')
return (donors)
def add_donation(donors, donator):
""" Add donation to donor
"""
while True:
prompt = "Please enter a valid amount to donate >"
donation = input(prompt)
if donation == "q":
return
try:
donation = float(donation)
except ValueError:
print('ValueError: Please enter a numeric value')
else:
if donation > 0:
break
else:
continue
donors[donator] = donors[donator] + [donation]
return donation
def create_card(donator, amount, fldr):
"""
Create thank you note for passed user
"""
donation_dict = {}
donation_dict['name'] = donator
donation_dict['donation'] = float(amount)
ty_text = 'Dear {name},\
\n\n\tThank you for your very kind donation of ${donation:,.2f}.\
\n\n\tIt will be put to very good use.\n\n\t\t\tSincerely,\
\n\t\t\t -The Team'.format(**donation_dict)
file_name = donation_dict['name'].replace(' ', '_') + '.txt'
file_path = os.path.join(fldr, file_name)
try:
with open(file_path, 'w+') as f:
f.write(ty_text)
except IOError:
print(f"IOError: Error writing to file: {write_path}")
print(f"\n** Thank you note to {donation_dict['name']} for ${donation_dict['donation']:,.2f} written to {write_path}. **\n")
return True
def send_ty(donors):
''' Send thank you to selected donor '''
donation = []
donor_prompt = "\n".join(("Enter Full name of donor",
" or Enter list to show current donors",
" Please enter donor name:"
" > "))
while True:
response = input(donor_prompt)
response = response.title()
if response.lower() == 'list':
list_donors(donors)
elif response == '':
continue
elif response in donors:
donation = add_donation(donors, response)
create_card(response, donation, write_path)
break
else:
donors[response] = []
donation = add_donation(donors, response)
create_card(response, donation, write_path)
break
return donors
def create_report(donors):
"""
Print formatted report of donors and donations
Sort report by total donations
"""
print("** You've selected to create a report. **\n")
report = []
col1 = 'Donor Name'
col2 = 'Total Given'
col3 = 'Num Gifts'
col4 = 'Average Gift'
# print(f'{col1:25} | {col2:13} | {col3:11} | {col4:13}')
# print('-'*70)
report.append(f'{col1:25} | {col2:13} | {col3:11} | {col4:13}')
report.append('-'*70)
donors = dict(sorted(donors.items(), key=sort_key, reverse=True))
for donor, donations in donors.items():
count = len(donations)
total = sum(donations)
avg = total/count
# print(f'{donor:25} ${total:13,.2f} {count:11} ${avg:12,.2f}')
report.append(f'{donor:25} ${total:13,.2f} {count:11} ${avg:12,.2f}')
report = '\n'.join(report)
print(report)
print("\n** Thank you! **\n")
def ask_for_folder():
global user_folder
# as creating folders is platform specific, end if not Windows.
import platform
if not platform.system().lower() == 'windows':
print(f'Sorry, future development requested but not currently enabled for {platform.system()} platform')
exit_program(0)
text = "\n".join(("\n\n\nEnter folder Name or hit enter for default",
" >"))
folder_prompt = input(text)
if folder_prompt:
user_folder = folder_prompt.replace(" ", "_")
else:
user_folder = default_folder
temp_path = tempfile.gettempdir()
folder_name = user_folder + '_' + today.strftime("%b_%d_%Y")
folder_path = os.path.join(temp_path, folder_name)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
return folder_path
def send_all_ty(donors):
'''
Create cards for all donor in dictionary
Note: revised code to use comprehension in Mailroom Part 3
'''
[create_card(donor, donations[-1], write_path) for donor, donations in donor_db.items()]
'''
for donor, donations in donors.items():
donation_current = donations[-1]
create_card(donor, donation_current, write_path)
'''
return donors
def exit_program(donors):
print('Thank you')
sys.exit()
def get_selection():
menu_prompt = "\n".join(("** Please Select Valid Option Listed: **",
" 1: Send a Thank You",
" 2: Create a Report",
" 3: Thanks to All Donors",
" 4: Quit",
f" (Folder: {user_folder})",
" Please enter your choice:"
" > "))
response = input(menu_prompt)
return response
if __name__ == '__main__':
try:
response = ''
write_path = ask_for_folder()
print(f'writing to file: {write_path}')
switch_func_dict = {
'1': send_ty,
'2': create_report,
'3': send_all_ty,
'4': exit_program
}
while True:
response = get_selection()
try:
# if response in switch_func_dict:
# switch_func_dict.get(response, "nothing")()
#switch_func_dict.get(response, "nothing")(donor_db)
switch_func_dict[response](donor_db)
# else:
# print("Please enter valid option")
except KeyError:
print('Please select a value 1-4')
except KeyboardInterrupt:
print('\n\nKeyboardInterrupt: Interrupted and Exiting')
sys.exit(0)
|
2675910b64a6e4b160b89eae697cd327d6cf2840 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/thecthaeh/Lesson08/test_circle_class.py | 2,482 | 3.65625 | 4 | #!/usr/bin/env python3
""" Test code for circle_class.py."""
import pytest
from circle_class import *
def test_radius():
c = Circle(4)
print(c.radius)
assert c.radius == 4
def test_diameter():
c = Circle(4)
print(c.diameter)
assert c.diameter == 8
def test_set_diameter():
c = Circle(4)
c.diameter = 2
print(c.diameter)
print(c.radius)
assert c.diameter == 2
assert c.radius == 1
def test_area():
c = Circle(4)
print(c.area)
assert round(c.area, 2) == 50.27
def test_set_area():
c = Circle(4)
with pytest.raises(AttributeError):
c.area = 42
print(c.area)
def test_from_diameter():
c = Circle.from_diameter(8)
print("Circle using diameter: ", c)
print(c.diameter)
assert c.diameter == 8
assert c.radius == 4
def test_print():
c = Circle(4)
print(c)
print(str(c))
print(repr(c))
assert str(c) == 'Circle with radius: 4'
assert repr(c) == 'Circle(4)'
def test_math():
c1 = Circle(2)
c2 = Circle(4)
print(repr(c1 + c2))
print(repr(c2 * 3))
print(repr(3 * c2))
assert repr(c1 + c2) == repr(Circle(6))
assert repr(c2 * 3) == repr(Circle(12))
assert repr(3 * c2) == repr(c2 * 3)
def test_compare():
c1 = Circle(2)
c2 = Circle(4)
c3 = Circle(4)
print(c1 > c2)
print(c1 < c2)
print (c2 == c3)
assert (c1 > c2) == False
assert c1 < c2
assert (c1 == c2) == False
assert c2 == c3
def test_sort_key():
circles = [Circle(2), Circle(4), Circle(4), Circle(3), Circle(8), Circle(6)]
print(circles)
circles.sort(key=Circle.sort_key)
print(circles)
assert circles == [Circle(2), Circle(3), Circle(4), Circle(4), Circle(6), Circle(8)]
#def test_sphere_subclass():
#add tests for sphere subclass
def test_sphere_print():
s = Sphere(4)
print(s)
print(str(s))
print(repr(s))
assert str(s) == 'Sphere with radius: 4'
assert repr(s) == 'Sphere(4)'
def test_sphere_volume():
s = Sphere(4)
print(s.volume)
assert round(s.volume, 2) == 268.08
def test_surface_area_sphere():
s = Sphere(4)
print(s.area)
assert round(s.area, 2) == 201.06
def test_from_diameter_sphere():
s = Sphere.from_diameter(8)
print("Sphere using diameter: ", s)
print(s.diameter)
assert s.diameter == 8
assert s.radius == 4 |
18b00b3737d11f8c89f2215d79fd0a8af746f105 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/tommy_bennett/lesson2/grid_printer.py | 394 | 3.9375 | 4 | def print_grid(w, h, n = 5):
for i in range(h):
print('+', end='')
for j in range(w):
print("-" * n + '+', end='')
print()
for i in range(3):
for j in range(w):
print("|" + ' ' * n, end='')
print('|')
print('+', end='')
for j in range(w):
print("-" * n + '+', end='')
print()
print_grid(5, 5)
|
b6a265e4836602f5165692a2bbbf1b090d038203 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/kimc05/Lesson03/strformat_lab.py | 2,138 | 4.1875 | 4 | #Christine Kim
#Python210 Lesson 3 String Formatting Lab Exercise
#Task One
#Given tuple
t1_tuple = (2, 123.4567, 10000, 12345.67)
#d for decimal integer, f for floating point, e for exponent notation, g for significant digits
t1_str = "file_{:03d} : {:.2f}, {:.2e}, {:.3g}".format(t1_tuple[0], t1_tuple[1], t1_tuple[2], t1_tuple[3])
#Verify result
print(t1_str)
#Task Two
t2_tuple = t1_tuple
t2_str = f"file_{t2_tuple[0]:03d} : {t2_tuple[1]:.2f}, {t2_tuple[2]:.2e}, {t2_tuple[3]:.3g}"
print(t2_str)
#Task Three
t3 = (2, 3, 5, 7, 9)
#Dynamic format build up method
def formatter(in_t):
#Accept only tuple
if type(in_t) == tuple:
#State the length of the numbers
form_string = f"the {len(in_t)} numbers are: "
#Perform action for every number in tuple
for num in in_t:
#add in format to base string
form_string += "{:d}, "
#return completed string after removing the last ', '
return form_string.format(*in_t)[:-2]
#Request new tuple
else:
print("Please verify your tuple.")
#Verify result
print(formatter(t3))
#Task Four
#Given tuple
t4 = (4, 30, 2017, 2, 27)
#Rearragned, position specified by index
#Option 1
Rearragned = "{:02d} " * len(t4)
print(Rearragned.format(t4[3],t4[4], t4[2], t4[0], t4[1]))
#Optoin 2
print(f"{t4[3]:02d} {t4[4]:d} {t4[2]:02d} {t4[0]:02d} {t4[1]:d}")
#Question: Which option is better?
#Task Five
list5 = ["oranges", 1.3, "lemons", 1.1]
#First print statement
print(f"The weight of an {list5[0][:-1]} is {list5[1]:.1f} and the weight of a {list5[2][:-1]} is {list5[3]:.1f}")
#Modified with 1.2 times weight and capitalized name
print(f"The weight of an {list5[0].upper()[:-1]} is {1.2 * list5[1]:.1f} and the weight of a {list5[2].upper()[:-1]} is {1.2 * list5[3]:.1f}")
#Task Six
#Write a table
fluff = [["Hammy", 9, "$35"], ["Teeny", 8, "$12"], ["Teeny2", 8, "$12"], ["Tiny", 8, "$15"], ["Jumbo", 6, "$75"], ["Jumbo Junior", 3, "$45"]]
for cute in fluff:
print("{:^12}{:^3}{:^3}".format(*cute))
#Write a column
t6 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
#Bonus
print(("{:>5}"*len(t6)).format(*t6)) |
53f2582b3d6deba0a783e0436351fcddefa95015 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mark-l-taylor/lesson04/trigrams.py | 3,907 | 4.21875 | 4 | #!/usr/bin/env python3
''' Trigram Assignment 3 from Lesson 04'''
import sys, random, string
#words = "I wish I may I wish I might".split()
def read_in_data(filename, start, end):
'''Reads in data and returns the lines from the source'''
lines = []
with open(filename, 'r') as f:
read_lines = False
for line in f:
if read_lines:
if line.startswith(end):
#End line found, stop processing lines
break
else:
#Otherwise add the line to the list, include rstrip to remove carriage returns
line = line.rstrip()
if line:
#Only add if line is not empty
lines.append(line)
elif line.startswith(start):
read_lines = True
print(f'Read in {len(lines)} from {filename}')
return lines
def make_words(lines):
'''Return a list of words from the lines'''
words = []
for line in lines:
#Remove the punctuation characters from the line
line = line.translate(str.maketrans('', '', string.punctuation))
words.extend(line.split(' '))
print(f'Processed {len(words)} words')
return words
def build_trigram(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]
seq = trigrams.get(pair,[])
seq.append(follower)
trigrams[pair] = seq
return trigrams
def random_key(dictionary):
'''Returns a random key from the dictionary'''
return random.choice(list(dictionary.keys()))
def build_sentence(tri_dict, sent_len):
''' Return a sentance built from a trigram. Sentance will be limited to length'''
word_pair = random_key(tri_dict)
print(sent_len)
#begin by adding the random starting word_pair to new_sent
new_sent = list(word_pair)
#loop through adding words from trigram to build a sentence.
while len(new_sent) < sent_len:
if word_pair in tri_dict:
#Get a random word from the value of the word_pair and append to new_sent
new_sent.append(random.choice(tri_dict[word_pair]))
#Determine the next word pair make into tuple to lookup in dictionary
word_pair = tuple(new_sent[-2:])
else:
#new word pair is not in list, get a new word pair and continue looping.
word_pair = random_key(tri_dict)
#Return the sentance to the input length
new_sent = new_sent[0:sent_len]
#Capitalize the first word
new_sent[0] = new_sent[0].capitalize()
#Add period to last word
new_sent[-1] = new_sent[-1] + '. '
return ' '.join(new_sent)
def build_text(tri_dict):
''' Create text based on the trigram dictionary'''
new_text = []
num_para = random.randint(3,6)
for i in range(1, num_para):
num_sent = random.randint(3,12)
for j in range(1, num_sent):
new_text.append(build_sentence(word_pairs, random.randint(8,30)))
j =+ 1
new_text.extend(['\n\n'])
i =+ 1
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)
header = '*** START OF THIS PROJECT GUTENBERG EBOOK'
end_line = '*** END OF THIS PROJECT GUTENBERG EBOOK'
in_data = read_in_data(filename, header, end_line)
words = make_words(in_data)
word_pairs = build_trigram(words)
new_text = build_text(word_pairs)
print(new_text)
|
e3e005313c7daec2afcfe89af80ee2adfaf30a9b | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/zach_thomson/lesson09/cli_main.py | 3,931 | 3.796875 | 4 | #!/usr/bin/env python3
from donor_models import *
import sys
prompt = '\n'.join(('Welcome to the mailroom',
'Please choose from the following options:',
'1 - Send a Thank You',
'2 - Create a Report',
'3 - Quit',
'> '))
#Initialize donor database
eddie = Donor('Eddie Vedder',[10000.00, 20000.00, 4500.00])
chris = Donor('Chris Cornell', [100.00, 500.00])
kurt = Donor('Kurt Cobain', [25.00])
daveM = Donor('Dave Matthews', [100000.00, 50000.00, 125000.00])
daveG = Donor('Dave Grohl', [50.00])
donor_db = DonorCollection(eddie, chris, kurt, daveM, daveG)
#send a thank you tasks
def initial_input():
'''Prompt user to query a name or ask for a list of the donors'''
ty_prompt = input('Please enter a full name or type list to see all the current donors: ')
return ty_prompt
def add_donor_prompt(name):
'''lets user chose if they want to add a donor as entered into the database'''
add_prompt = input('Do you want to add a new entry from {} to the donor list? (Yes/No)'.format(name))
if add_prompt.lower() == 'yes':
return True
elif add_prompt.lower() == 'no':
return False
else:
return add_donor_prompt(name)
def donation_prompt():
'''Prompt user to enter a donation amount'''
donation = input('Please enter a donation amount: ')
return donation
def int_donation_text():
'''Print statement for when user inputs a non-integer'''
print('Please enter an integer for the donation amount.')
def neg_donation():
'''Print statement for when user inputs donation less than zero'''
print('Donation should be greater than zero!')
def thank_you():
'''Main thank you function'''
thank_you_logic(initial_input())
def donation_logic(name, donation):
'''Determines if donation is valid and then creates a new donor'''
try:
donation = float(donation)
except ValueError:
int_donation_text()
else:
try:
assert donation > 0
except AssertionError:
neg_donation()
else:
donor_db.new_donation(name, donation)
def donor_list():
'''Simple print function for list of donors'''
print(donor_db.donors.keys())
def donor_not_added():
'''Simple print function for not adding a donor'''
print('Donor not added!')
def thank_you_logic(name):
'''determines if donor is in database and either appends donation amount
or creates a new donor in the database'''
if name.lower() == 'list':
donor_list()
else:
if name not in donor_db.donors.keys():
add = add_donor_prompt(name)
if add == True:
donation_logic(name, donation_prompt())
else:
donor_not_added()
else:
donation_logic(name, donation_prompt())
#Create a report tasks
def create_report():
'''formats get_report into the create_report format'''
header = ('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')
table_header = "{:<20}| {} | {} | {}".format(*header) + '\n' + "-" * 60
line_format = ("{:<20}" + " $" + "{:>12.2f}" + "{:>11}" + " $" + "{:>12.2f}")
print(table_header)
table = donor_db.get_report()
for entry in table:
print(line_format.format(*entry))
#make a function to exit the program
def exit_program():
print('Have a nice day!')
sys.exit() # exit the interactive script
switch_dict = {1: thank_you,
2: create_report,
3: exit_program,
}
def main():
while True:
response = input(prompt)
try:
response = int(response)
except ValueError:
print('Please input a valid response')
else:
try:
switch_dict.get(int(response))()
except TypeError:
print('Please input a valid response')
if __name__ == "__main__":
main()
|
d49ab47b15ea9d4d3033fc86dc627cdc019444a9 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/brgalloway/Lesson_5/except_exercise.py | 1,268 | 4.15625 | 4 | #!/usr/bin/python
"""
An exercise in playing with Exceptions.
Make lots of try/except blocks for fun and profit.
Make sure to catch specifically the error you find, rather than all errors.
"""
from except_test import fun, more_fun, last_fun
# Figure out what the exception is, catch it and while still
# in that catch block, try again with the second item in the list
first_try = ['spam', 'cheese', 'mr death']
try:
# spam triggers Nameerror since s is not defined
joke = fun(first_try[0])
except NameError:
# calling fun again with cheese yields expected results
joke = fun(first_try[1])
# Here is a try/except block. Add an else that prints not_joke
try:
# fun runs and assisngs value to not_joke
not_joke = fun(first_try[2])
except SyntaxError:
print('Run Away!')
else:
# printing the returned value after
# running fun with third element in first_try
print(not_joke)
#
langs = ['java', 'c', 'python']
try:
# java triggers the IndexError
# since test is only 3 elements long
more_joke = more_fun(langs[0])
except IndexError:
# after indexerror more_fun runs with c
more_joke = more_fun(langs[1])
else:
print("index error")
finally:
# then finally running the last function
last_fun()
|
64ffaf3c5852e641e5ef292fc74dea57d079b7e1 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/choltzman/lesson08/test_circle.py | 1,280 | 3.828125 | 4 | #!/usr/bin/env python3
from circle import Circle, Sphere
def test_radius():
c = Circle(4)
assert c.radius == 4
def test_diameter_getter():
c = Circle(4)
assert c.diameter == 8
def test_diameter_setter():
c = Circle(4)
c.diameter = 10
assert c.radius == 5
def test_area():
c = Circle(4)
assert c.area == 50.26548245743669
def test_from_diameter():
c = Circle.from_diameter(8)
assert c.radius == 4
def test_str():
c = Circle(4)
assert str(c) == "Circle with radius: 4.0"
def test_repr():
c = Circle(4)
assert repr(c) == "Circle(4.0)"
assert eval(repr(c)) == Circle(4)
def test_addition():
assert Circle(4) + Circle(8) == Circle(12)
def test_multiplication():
assert Circle(4) * 2 == Circle(8)
assert 2 * Circle(4) == Circle(8)
def test_comparison():
assert Circle(4) == Circle(4)
assert Circle(4) < Circle(8)
assert Circle(4) <= Circle(8)
assert Circle(8) > Circle(4)
assert Circle(8) >= Circle(4)
def test_sort():
clist = [Circle(8), Circle(4)]
assert sorted(clist) == [Circle(4), Circle(8)]
def test_volume():
s = Sphere(4)
assert s.volume == 268.082573106329
def test_sphere_area():
s = Sphere(4)
assert s.area == 201.06192982974676
|
3559a141a2d051c4f05936aeafcb177da8921195 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Kollii/lesson03/strformat_lab.py | 2,531 | 4.15625 | 4 |
# Task One
"""a format string that will take the following four element tuple:
( 2, 123.4567, 10000, 12345.67)
and produce:
'file_002 : 123.46, 1.00e+04, 1.23e+04'
"""
print("## Task One ##\n")
string = (2, 123.4567, 10000, 12345.67)
print("A string: ", string)
formated_str = "file_{:03d} : {:10.2f}, {:.2e}, {:.3g}".format(2, 123.4567, 10000, 12345.67)
print("Fromated string: ", formated_str)
# Task Two
print("\n## Task Two ##\n")
#alternative method to achieve task one
print("alternate type of format string\n")
print(f"file_{string[0]:0>3d} : {string[1]:.2f}, {string[2]:.2e}, {string[3]:.3e}")
# Task Three
print("\n## Task Three ##\n")
print("Dynamically Building up format strings\n")
def formatter(in_tuple):
count = len(in_tuple)
str_output = ('the {} numbers are: ' +
', '.join(['{:d}'] * count)).format(count,*in_tuple)
return str_output
tuple1= (2,3,5)
tuple2 = (2,3,5,7,9)
print(formatter(tuple1))
print(formatter(tuple2 ))
# Task Four
print("\n## Task Four ##\n")
# given a 5 element tuple ( 4, 30, 2017, 2, 27)
# use string formating to print: '02 27 2017 04 30'
tuple4 = (4, 30, 2017, 2, 27)
print("{3:0>2d} {4:0} {2:0} {0:0>2d} {1:0}".format(*tuple4))
# Task Five
print("\n## Task Five ##\n")
# Here’s a task : Given the following four element list: ['oranges', 1.3, 'lemons', 1.1]
# Write an f-string that will display: The weight of an orange is 1.3 and the weight of a lemon is 1.1
list1 = ['oranges', 1.3, 'lemons', 1.1]
print("f-string: ", f'The weight of an {list1[0][:-1]} is {list1[1]} and the weight of a {list1[2][:-1]} is {list1[3]}')
print("change the f-string so that it displays the names of the fruit in upper case, and the weight 20% higher (that is 1.2 times higher)")
print(f'The weight of an {list1[0].upper()[:-1]} is {list1[1] * 1.2} '
f'and the weight of a {list1[2].upper()[:-1]} is {list1[3] * 1.2}')
# Task Six
print("\n## Task Six ##\n")
print(" print a table of several rows, each with a name, an age and a cost ")
tuple6 = list()
tuple6.append(("Abc", 25, 12345))
tuple6.append(("Xyzh", 35, 4567))
tuple6.append(("Pqrst", 45, 6789))
tuple6.append(("Mnopsdf", 15, 2345))
for t in tuple6:
print('{:10}{:5}{:15.{d}f}'.format(*t, d=2))
#extra task: given a tuple with 10 consecutive numbers, print tuple in columns that are 5 char wide
tuple_extra = (1,2,3,4,5,6,7,8,9,10)
print("given a tuple with 10 consecutive numbers, print tuple in columns that are 5 char wide")
print(('{:{wide}}'*10).format(*tuple_extra, wide=5))
|
10ea434aca91510ed2a7818567fa782279ca79b2 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/kyle_odonnell/Lesson03/list_lab.py | 3,143 | 4.40625 | 4 | #!/usr/bin/env python3
# Series 1
print("********* Series 1 ************")
# Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”
fruit_list = ["Apples", "Pears", "Oranges", "Peaches"]
# Display the list
print(fruit_list)
# Ask the user for another fruit and add it to the end of the list.
new_fruit = input("What else would you like to add to your Fruit List? ")
fruit_list.append(new_fruit.title())
print(fruit_list)
# Ask the user for a number and display the number back to the user and the fruit corresponding to that number
num = int(input("Please choose an integer number "))
try:
print(F'Item {num} is {fruit_list[num-1]}')
except IndexError:
print("Number outside list range")
# Add another fruit to the beginning of the list using “+” and display the list
fruit_list = fruit_list + ["Blueberries"]
print("Added blueberries using concatenate:")
print(fruit_list)
# Add another fruit to the beginning of the list using insert() and display the list
fruit_list.insert(0, "Raspberries")
print("Added Raspberries using insert method:")
print(fruit_list)
print("Fruits in list that start with p: ")
for f in fruit_list:
if f[0].lower() == "p":
print(f)
print("********* Series 2 *********")
fruit_list = ["Apples", "Pears", "Oranges", "Peaches"]
# Display the list
print("Fruit List:")
print(fruit_list)
# Remove the last fruit from the list
del fruit_list[-1]
# Display the list
print("List with last item removed:")
print(fruit_list)
# Ask the user for a fruit to delete, find it and delete it.
remove_fruit = input("What would you like to remove? ").title()
fruit_list.remove(remove_fruit)
print("Removed {} from list:".format(remove_fruit))
print(fruit_list)
# Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.)
print("** Bonus **")
fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] * 2
while True:
print("Fruit list:", fruit_list)
fruit = input("Enter a fruit to remove from list: ").title()
if fruit in fruit_list:
for f in fruit_list:
if f == fruit:
fruit_list.remove(f)
break
else:
print("Please select fruit from the list.")
print("Removed {} from list".format(fruit))
print(fruit_list)
print("********* Series 3 *********")
fruit_list = ["Apples", "Pears", "Oranges", "Peaches"]
likes = []
for f in fruit_list:
while True:
taste = input("Do you like {}? ".format(f.lower()))
if taste.lower() == "no":
break
elif taste.lower() == "yes":
likes.append(f)
break
else:
print("Please enter yes or no")
fruit_list = likes
print("New list with only liked fruit:", fruit_list)
print("********* Series 4 *********")
fruit_list = ["Apples", "Pears", "Oranges", "Peaches"]
print("Original List:", fruit_list)
fruit_list_reverse = []
for f in fruit_list:
fruit_list_reverse.append(f[::-1].title())
fruit_list.pop(-1)
print("Original List without last item", fruit_list)
print("New list with items spelled backwards:", fruit_list_reverse) |
72d0a8f8f633fdab5ee16a92b9b880df63ec460a | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Shweta/Lesson07/html_render.py | 3,618 | 3.515625 | 4 | #!/usr/bin/env python
import copy
"""
A class-based system for rendering html.
"""
# This is the framework for the base class
class Element(object):
tag="html"
indent = " "
def __init__(self, content=None, **kwargs):
self.kwargs = kwargs
self.contents=[]
if content is not None:
self.contents= [content]
def append(self, n_content):
self.contents.append(n_content)
def _open_tag(self,out_file):
open_tag = ["<{}".format(self.tag)]
for key in self.kwargs:
open_tag.append(" " + key + "=" + '"'+ str(self.kwargs[key]) + '"')
out_file.write("".join(open_tag))
def render(self, out_file,cur_ind=""):
open_tag = ["<{}>".format(self.tag)]
#open_tag.append(">\n")
for key in self.kwargs:
open_tag.append(" " + key + "=" + str(self.kwargs[key]))
out_file.write("".join(open_tag))
for content in self.contents:
try:
content.render(out_file,cur_ind+self.indent)
except AttributeError:
out_file.write("{}".format(cur_ind + self.indent))
out_file.write(content)
out_file.write("</{}>\n".format(self.tag))
class Html(Element):
tag="html"
indind=0
def render(self,out_file,cur_ind=""):
self.cur_ind=cur_ind+str(self.indent*self.indind)
#self.contents.insert(0,'<!DOCTYPE html>\n')
open_tag = ["<{}>\n".format(self.tag)]
out_file.write("".join('<!DOCTYPE html>\n'))
out_file.write("".join(open_tag))
for content in self.contents:
try:
content.render(out_file)
except AttributeError:
out_file.write("{}".format(cur_ind + self.indent))
out_file.write(content)
out_file.write("\n")
out_file.write("</{}>\n".format(self.tag))
class Body(Element):
tag="body"
class P(Element):
tag="p"
class Head(Element):
tag="head"
class OneLineTag(Element):
def render(self,out_file,cur_ind=""):
out_file.write("<{}>".format(self.tag))
out_file.write(self.contents[0])
out_file.write("</{}>\n".format(self.tag))
def append(self,content):
raise NotImplementedError
class Title(OneLineTag):
tag="title"
class SelfClosingTag(Element):
def __init__(self, content=None, **kwargs):
self.content = []
self.kwargs = kwargs
if content is not None:
raise TypeError("SelfClosing can not contain any content")
super().__init__(content=content,**kwargs)
def append(self,content):
raise TypeError("You can not add content to selfclosingtag")
def render(self,out_file,cur_ind=''):
self._open_tag(out_file)
for content in self.contents:
try:
content.render(out_file)
except AttributeError:
out_file.write(content)
out_file.write("\n")
out_file.write(" />\n")
class Hr(SelfClosingTag):
tag="hr"
class Br(SelfClosingTag):
tag="br"
class Meta(SelfClosingTag):
tag='meta charset="UTF-8"'
class A(OneLineTag):
tag='a href'
def __init__(self,link,content=None,**kwargs):
#kwargs['href']=link
super().__init__(content,**kwargs)
class Ul(Element):
tag="ul"
class Li(Element):
tag="li"
class H(OneLineTag):
tag="h"
def __init__(self,head_no,content=None,**kwargs):
self.tag=self.tag + str(head_no)
super().__init__(content,**kwargs)
#Element([])
|
9be9aa72f25c4549157fb247a7860db60657343f | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/chasedullinger/lesson02/series.py | 1,911 | 4.0625 | 4 | # PY210 Lesson 02 Fibonacci Series Exercise - Chase Dullinger
def fibonacci(n):
"""Given n, returns the nth value of the Fibonacci series"""
if n == 0:
return 0
if n == 1:
return 1
result = fibonacci(n-2)+fibonacci(n-1)
return result
def lucas(n):
"""Given n, returns the nth value of the Lucas series"""
if n == 0:
return 2
if n == 1:
return 1
result = lucas(n-2)+lucas(n-1)
return result
def sum_series(n, n0=0, n1=1):
"""Given n, returns the nth value of the series defined by f(n)=f(n-2)+f(n-1).
:param n0=0: is the value of the 0th position n
:param n1=0: is the value of the 1st position n
default values of n0=0 and n1=1 will give the Fibonacci series
"""
if n == 0:
return n0
if n == 1:
return n1
result = sum_series(n-2, n0, n1)+sum_series(n-1, n0, n1)
return result
if __name__=="__main__":
#check that fibonacci() returns known values for the fibonacci series
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
#check that lucas() returns known values for the lucas series
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("tests passed")
|
687920bd4cb0dd3b4662157f10df37e32c0454fa | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mimalvarez_pintor/lesson06/test_random_pytest.py | 1,176 | 3.515625 | 4 | #!/usr/bin/env python
"""
port of the random unit tests from the python docs to py.test
"""
import random
import pytest
example_seq = list(range(10))
def test_choice():
"""
A choice selected should be in the sequence
"""
element = random.choice(example_seq)
assert (element in example_seq)
def test_sample():
"""
All the items in a sample should be in the sequence
"""
for element in random.sample(example_seq, 5):
assert element in example_seq
def test_shuffle():
"""
Make sure a shuffled sequence does not lose any elements
"""
seq = list(range(10))
random.shuffle(seq)
# seq.sort() # If you comment this out, it will fail, so you can see output
print("seq:", seq) # only see output if it fails
assert seq == list(range(10))
def test_shuffle_immutable():
"""
Trying to shuffle an immutable sequence raises an Exception
"""
with pytest.raises(TypeError):
random.shuffle((1, 2, 3))
def test_sample_too_large():
"""
Trying to sample more than exist should raise an error
"""
with pytest.raises(ValueError):
random.sample(example_seq, 20)
|
95823308e9d66ce9d661e91e1a3df756379d3cf8 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/shervs/lesson04/trigrams.py | 2,497 | 3.96875 | 4 | #!/usr/bin/env python
import random
import sys
def read_in_data(in_filename):
with open(in_filename) as infile:
in_lines = infile.readlines()
return in_lines
def make_words(in_lines):
in_words = []
for line in in_lines:
#Remove headers and footers
if line[0:3] == '***':
in_lines.remove(line)
#Remove punctuation
else:
new_line = line.translate(str.maketrans(
'''0123456789!"#$%&()*+,-./:;<=>?@[\]^_`{|}~'''
,' ' ))
#Break each line to wrods and feed into the word list
for word in new_line.split():
if word is not "I":
word = word.lower()
in_words.append(word)
return in_words
def build_trigrams(words):
trigrams = {}
for i in range(len(words)-2):
pair = words[i:i + 2]
follower = words[i + 2]
trigrams.setdefault(tuple(pair),[]).append(follower)
return trigrams
def build_text(trigrams):
word_limit = int(input('Enter the desired number of words in the new text\
(minimum of 3)>'))
#Pick the first random word pair from the dictionay
first_pair = random.choice(list(trigrams))
new_list = list(first_pair)
new_list.append(random.choice(trigrams[first_pair]))
#add a new word to the list using the last two words in the list as
#word pairs
count = 3
while count < word_limit:
if tuple(new_list[-2:]) in trigrams:
new_list.append(random.choice(trigrams[tuple(new_list[-2:])]))
count += 1
elif count == word_limit-1:
new_list.append(first_pair[0])
count += 1
elif count == word_limit-2:
new_list.append(first_pair[0])
new_list.append(first_pair[1])
count += 2
else:
new_list.append(first_pair[0])
new_list.append(first_pair[1])
new_list.append(random.choice(trigrams[first_pair]))
count += 3
new_text = " ".join(new_list)
return 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)
in_data = read_in_data(filename)
words = make_words(in_data)
word_pairs = build_trigrams(words)
new_story = build_text(word_pairs)
print(new_story) |
ea194097dee6ee3c57267d60835892c923316f6d | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Steven/lesson04/trigrams.py | 1,998 | 4.34375 | 4 | #! bin/user/env python3
import random
words = "I wish I may I wish I might".split() # a list
filename = r"C:\Users\smar8\PycharmProjects\Python210\lesson04\sherlock_small.txt"
def build_trigrams(words):
trigrams = {}
# build up the dict here!
for word in range(len(words)-2): # stops with the last two words in the list
pair = (words[word], words[word+1]) # Pair of words stored in a tuple
follower = words[word+2] # set the 3 word
trigrams.setdefault(pair, []).append(follower)
# print(trigrams)
return trigrams
# creating the words list from a file
def make_words(file):
with open(file, 'r') as fh:
# for line in fh:
text = fh.read()
punc = ('.', ',', '!', '?', '-', "'", '(', ')')
for word in text:
if word in punc:
text = text.replace(word, ' ') # remove punctuation from the file
text = text.split()
# print(text)
return text
def build_text(db, n): # params of word list and number of words to read
book = ""
key = random.choice(list(db.keys())) # select a random key from the sequence
temp = list(key)
for number in range(n):
nextWord = (db[key][random.randint(0, (len(db[key]) - 1))]) # select the value of the key pair from a random number based on the length of the keys of input seq
temp.append(nextWord)
key = tuple(temp[-2:])
story = " ".join(temp) # combine all the words
story = story.split(".") # Split each line when there is a period
for item in story:
book += (item[0].capitalize() + item[1:] + ".") # Make each sentence start with a capital letter and end with a period
return book
if __name__ == "__main__":
filename = r"C:\Users\smar8\PycharmProjects\Python210\lesson04\sherlock_small.txt"
n = 10 # number of key pairs of words to read from the file
words = make_words(filename)
trigrams = build_trigrams(words)
new_text = build_text(trigrams, n)
print(new_text) |
0c47d864adfe1e2821609c2d4d3e1b312790127f | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/steve-long/lesson02-basic-functions/ex-2-2-fizzBuzz/fizzBuzz.py | 2,557 | 4.21875 | 4 | #!/usr/bin/env python3
# ========================================================================================
# Python210 | Fall 2020
# ----------------------------------------------------------------------------------------
# Lesson02
# Fizz Buzz Exercise (fizzBuzz.py)
# Steve Long 2020-09-19 | v0
#
# Requirements:
# -------------
# Write a program that prints the numbers from 1 to 100 inclusive.
# But for multiples of three print "Fizz" instead of the number.
# For the multiples of five print "Buzz" instead of the number.
# For numbers which are multiples of both three and five print "FizzBuzz" instead.
#
# Implementation:
# ---------------
# fizzBuzz([<start>[,<end>]])
#
# Script Usage:
# -------------
# python fizzBuzz.py [<start> [<end>]]
# <start> ::= Starting number (see function fizzBuzz for details.)
# <end> ::= Ending number (see function fizzBuzz for details.)
#
# History:
# --------
# 000/2020-09-20/sal/Created.
# ========================================================================================
import sys
def fizzBuzz(start = 1, end = 100):
"""
fizzBuzz([<start>[,<end>]])
--------------------------------------------------------------------------------------
For non-negative int values from <start> to <end>, print the following:
* "Fizz" for multiples of 3
* "Buzz" for multiples of 5
* "FizzBuzz" for multiples of 3 and 5
* The number for all other values
Entry: <start> ::= Starting int value (default is 1).
<end> ::= Ending int value (default is 100).
Exit: Returns True.
"""
for n in range(start, (end + 1)):
s = ("FizzBuzz" if (((n % 3) == 0) and ((n % 5) == 0)) else \
("Fizz" if ((n % 3) == 0) else \
("Buzz" if ((n % 5) == 0) else n)))
print(s)
return True
# Command-line interface for demonstrating function fizzBuzz.
if __name__ == "__main__":
args = sys.argv
argCount = (len(args) - 1)
if (argCount == 2):
#
# Execute validated 2-argument scenario.
#
if (args[1].isnumeric() and args[2].isnumeric()):
fizzBuzz(int(args[1]), int(args[2]))
else:
if (not args[1].isnumeric()):
print("fizzBuzz (ERROR): Invalid start argument ({})".format(args[1]))
if (not args[2].isnumeric()):
print("fizzBuzz (ERROR): Invalid end argument ({})".format(args[2]))
elif (argCount == 1):
#
# Execute validated 1-argument scenario.
#
if (args[1].isnumeric()):
fizzBuzz(int(args[1]))
else:
print("fizzBuzz (ERROR): Invalid start argument ({})".format(args[1]))
else:
#
# Execute validated 0-argument scenario.
#
fizzBuzz()
|
a344005c47bf8ef97565b588cc6b430596f517c6 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/nam_vo/lesson01/task2.py | 273 | 3.765625 | 4 | def pos_neg(a, b, negative):
if negative:
return a < 0 and b < 0
else:
return a*b < 0
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:]
|
2bbde4f032d7a208024770b087c7f765fedac131 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mattcasari/lesson01/warmup-1/front_back.py | 151 | 3.9375 | 4 | #!/usr/bin/python
# -*- coding: ascii -*-
def front_back(str1):
if len(str1) > 1:
str1 = str1[-1] + str1[1:-1] + str1[0]
return str1 |
e5b9b3bd73ee725a3bc22ddaaf13433dc0cc4d3d | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/brgalloway/Lesson_3/mailroom_part_1.py | 3,146 | 3.875 | 4 | import sys
from operator import itemgetter, attrgetter
# TODO
# 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.
# The script should prompt the user (you) to choose
# from a menu of 3 actions: “Send a Thank You”, “Create a Report” or “quit”.
donors_list = [
["Jeff Bezos", 877.33, 1, 877.33],
["Paul Allen", 708.42, 3, 236.14],
["William Gates, III", 653784.49, 2, 326892.24],
["Bill Ackman", 2354.05, 3, 784.68],
["Mark Zuckerberg", 16396.10, 3, 5465.37]
]
# Main function to get users input
def main_prompt():
display_menu = "Choose one of the following options. \n\n" \
"1 - Send a Thank You \n" \
"2 - Create a Report \n" \
"3 - Quit \n"
while True:
print(display_menu)
prompt = input("Enter a choice to continue: ")
if prompt == "1":
sub_menu()
elif prompt == "2":
generate_report(donors_list)
elif prompt == "3":
sys.exit()
else:
print("Enter a valid response")
def sub_menu():
while True:
fullname = input("Enter the full name of the donor or type list to display names\n" \
"Typing quit will take you to the main menu\n" \
">> ")
if fullname == "list":
return list_names()
elif fullname == "quit":
return main_prompt()
elif fullname:
return send_thankyou(fullname)
else:
print("Enter a valid response")
def list_names():
donors_list.sort()
for i in donors_list:
print(i[0])
print("-" * 12)
return
# Generate report based on menu choice
# and return user to the menu prompt
def generate_report(donors_list):
sorted_list = sorted(donors_list, key=itemgetter(1), reverse=True)
print("{:<20}|{:^18}|{:^15}|{:^15}".format("Donor Name", "Total Given", "Num Gifts", "Average Gifts"))
print("-" * 70)
for i in sorted_list:
print(f"{i[0]:<20}${i[1]:>14.2f}{i[2]:^18}${i[3]:>12.2f}".format())
# This function sends the formatted email
# records donation amounts and adds new users
# and their donaitons to the database
def send_thankyou(fullname,donors_list=donors_list):
donation_amount = float(input("Donation amount: "))
for donor in donors_list:
if fullname == donor[0]:
donor[1] = donor[1] + donation_amount
donor[2] = donor[2] + 1
donor[3] = donor[1] / donor[2]
donors_list[donors_list.index(donor)] = [donor[0], donor[1], donor[2], donor[3]]
break
else:
donors_list.append([fullname, donation_amount, 1, donation_amount])
email = f"Dear {fullname},\n\nThank you for your very kind donation of ${donation_amount:.2f}.\n\n" \
"It will be put to very good use.\n\n" \
"Sincerely,\n" \
"-The Team"
print(email)
if __name__ == '__main__':
main_prompt() |
c6859f649d7220dcd0ecadec0bd9c05a6de9e109 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jinee_han/lesson09/cli_main.py | 3,584 | 3.6875 | 4 | import donor_models as donor_models
import sys
donor_collection = donor_models.DonorCollection()
# Display options
prompt = "\n".join(("Welcome to the donor list!",
"Please choose from below options:",
"1 - Send a Thank you",
"2 - Create a Report",
"3 - Exit",
">>> "))
def display_list():
'''
Display the list of current donors
:return: prints donor names
'''
for d in donor_collection.donors:
print(d.donor_name)
def send_thank_you_note():
'''
Check for the user input and send a thank you once user entered
:return: nothing
'''
input_value = input("Enter a full name. (Type 'list' to see the donor list)") # Ask the name
while input_value == 'list':
display_list()
input_value = input("Enter a full name. (Type 'list' to see the donor list)")
# Store the donor name with the first character as an upper case letter
donor_name = input_value.title()
donor_not_present = False
new_donor = None
if not donor_collection.donor_present(donor_name):
donor_not_present = True
new_donor = donor_models.Donor(donor_name)
else:
new_donor = next((d for d in donor_collection.donors if d.donor_name == donor_name), None)
donation_amount = None
while donation_amount is None:
try:
donation_amount = float(input("Please enter the donation amount: "))
if (donation_amount <= 0):
print ("Please enter a donation amount larger than zero.")
donation_amount = None
pass
except ValueError:
print ("Please enter a valid donation amount.")
pass
new_donor.add_donation(donation_amount)
if donor_not_present:
donor_collection.add_donor(new_donor)
# send thank you
print(new_donor.format_thank_you_note(donation_amount))
def create_report():
'''
Create the donor report
:return: Print donor report to console
'''
print(donor_collection.create_report())
def exit_program():
'''
Exit the program
:return: nothing
'''
print("Thank you for your donations!")
sys.exit() # exit the interactive script
def initialize_donors():
'''
Initialize the donor collection with the same donors and amounts as Mailroom1
now using the newly created objects
:return: void
'''
donor_kim = donor_models.Donor("Kim Kardasian")
donor_kim.add_donation(653772.32, 12.17)
donor_kendal = donor_models.Donor("Kendal Jenner")
donor_kendal.add_donation(877.33)
donor_gigi = donor_models.Donor("Gigi Hadid")
donor_gigi.add_donation(663.23, 43.87, 1.32)
donor_justin = donor_models.Donor("Justin Bieber")
donor_justin.add_donation(1663.23, 4300.87, 10432.0)
donor_will = donor_models.Donor("Will Smith")
donor_will.add_donation(43.23, 4000.07, 183423.2)
donor_collection.add_donor(donor_kim, donor_kendal, donor_gigi, donor_justin, donor_will)
input_dict = {1: send_thank_you_note, 2: create_report, 3: exit_program}
def main():
'''
Run the main function to handle user input and displaying options
:return: void
'''
initialize_donors()
while True:
try:
response = int(input(prompt)) # continuously collect user selection
input_dict.get(response)()
except TypeError:
print("Please enter a number between 1 - 3.\n")
except ValueError:
print("Please enter a number between 1 - 3.\n")
if __name__ == "__main__":
main() |
0cf9e964e6c38573cb01357571f6411dfa344dc2 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/chasedullinger/lesson06/test_arguments.py | 4,484 | 4.03125 | 4 | """
test code for argument examples
"""
import arguments
def test_kw_args_with_defaults():
"""Test function with default args"""
assert arguments.fun_opt_kw_params() == ('blue', 'red', 'yellow', 'orange')
def test_kw_args_with_positional():
"""Test function with positional args"""
assert arguments.fun_opt_kw_params('blue', 'red', 'yellow',
'orange') == ('blue', 'red', 'yellow',
'orange')
def test_kw_args_with_keywords():
"""Test function with keyword args"""
assert arguments.fun_opt_kw_params(visited_color='blue',
link_color='red',
back_color='yellow',
fore_color='orange') == ('orange',
'yellow',
'red', 'blue')
def test_kw_args_with_tuple():
"""Test function with tuple args"""
arg_tuple = ('blue', 'red', 'yellow', 'orange')
assert arguments.fun_opt_kw_params(*arg_tuple) == ('blue', 'red', 'yellow',
'orange')
def test_kw_args_with_dict():
"""Test function with dict args"""
arg_dict = {'visited_color': 'blue',
'link_color': 'red',
'back_color': 'yellow',
'fore_color': 'orange'}
assert arguments.fun_opt_kw_params(**arg_dict) == ('orange', 'yellow',
'red', 'blue')
def test_kw_args_with_tuple_and_dict():
"""Test function with tuple and dict args"""
arg_tuple = ('orange', 'yellow')
arg_dict = {'visited_color': 'blue',
'link_color': 'red'}
assert arguments.fun_opt_kw_params(*arg_tuple, **arg_dict) == ('orange',
'yellow',
'red',
'blue')
def test_star_args_with_star_args():
"""Test function with *args and **kwargs args"""
assert arguments.fun_star_params('orange', 'yellow', visited_color='red',
link_color='blue') == ('orange',
'yellow',
'red',
'blue')
def test_star_args_with_positional():
"""Test function with positional args"""
assert arguments.fun_star_params('blue', 'red', 'yellow',
'orange') == ('blue', 'red', 'yellow',
'orange')
def test_star_args_with_keywords():
"""Test function with keyword args"""
assert arguments.fun_star_params(visited_color='orange',
link_color='yellow',
back_color='red',
fore_color='blue') == ('orange',
'yellow',
'red', 'blue')
def test_star_args_with_tuple():
"""Test function with tuple args"""
arg_tuple = ('blue', 'red', 'yellow', 'orange')
assert arguments.fun_star_params(*arg_tuple) == ('blue', 'red', 'yellow',
'orange')
def test_star_args_with_dict():
"""Test function with dict args"""
arg_dict = {'visited_color': 'orange',
'link_color': 'yellow',
'back_color': 'red',
'fore_color': 'blue'}
assert arguments.fun_star_params(**arg_dict) == ('orange', 'yellow',
'red', 'blue')
def test_star_args_with_tuple_and_dict():
"""Test function with tuple and dict args"""
arg_tuple = ('orange', 'yellow')
arg_dict = {'visited_color': 'red',
'link_color': 'blue'}
assert arguments.fun_star_params(*arg_tuple, **arg_dict) == ('orange',
'yellow',
'red',
'blue')
|
f7e80e6496aa629ce1d723a1b05c348c50e09bc7 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/zach_thomson/lesson03/mailroom.py | 3,117 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
donor_db = [('Eddie Vedder', [10000.00, 20000.00, 4500.00]),
('Chris Cornell', [100.00, 500.00]),
('Kurt Cobain', [25.00]),
('Dave Matthews', [100000.00, 50000.00, 125000.00]),
('Dave Grohl', [50.00])]
prompt = '\n'.join(('Welcome to the mailroom',
'Please choose from the following options:',
'1 - Send a Thank You',
'2 - Create a Report',
'3 - Quit',
'> '))
#send a thank you tasks
def donor_names():
"""return a list of names in the donor database"""
donor_list = []
for donor in donor_db:
donor_list.append(donor[0])
return donor_list
def thank_you():
ty_prompt = input('Please enter a full name or type list to see all the current donors: ')
while ty_prompt.lower() == 'list':
print(donor_names())
ty_prompt = input('Please enter a full name or type list to see all the current donors: ')
else:
donation_amount = float(input('Please enter a donation amount: '))
for idx, donor in enumerate(donor_db):
if donor[0] == ty_prompt:
donor_db[idx][1].append(donation_amount)
break
else:
new_entry = (ty_prompt, [donation_amount])
donor_db.append(new_entry)
donation_email = "\nDear {},\nThank you for your generous donation of ${:.2f}!\n"
print(donation_email.format(ty_prompt, donation_amount))
#create a report functions
def number_donations(idx):
return len(donor_db[idx][1])
def average_gift(idx):
return sum(donor_db[idx][1])/len(donor_db[idx][1])
def sum_second(elem):
total = 0
for i in elem[1]:
total = i + total
return total
def second_sort(elem):
return elem[1]
def create_table():
"""takes the donor database and sorts on total given. also makes a summary
table with total given, number of gifts and average amount of gift"""
report_table = []
i = 0
while i < len(donor_db):
new_entry = (donor_db[i][0], sum(donor_db[i][1]), number_donations(i), average_gift(i))
report_table.append(new_entry)
i = i + 1
report_table.sort(key = second_sort, reverse = True)
return report_table
def create_report():
'''formats create_table into the create_report format'''
header = ('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')
table_header = "{:<20}| {} | {} | {}".format(*header) + '\n' + "-" * 60
line_format = ("{:<20}" + " $" + "{:>12.2f}" + "{:>11}" + " $" + "{:>12.2f}")
print(table_header)
table = create_table()
for entry in table:
print(line_format.format(*entry))
#make a function to exit the program
def exit_program():
print('Have a nice day!')
sys.exit() # exit the interactive script
def main():
while True:
response = input(prompt)
if response == '1':
thank_you()
elif response == '2':
create_report()
elif response == '3':
exit_program()
else:
print('Not a valid option')
if __name__ == "__main__":
main()
|
cdc25e57ddb2dd939af4f15187168f536709691e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/adam_strong/lesson04/trigrams.py | 2,281 | 3.96875 | 4 | #!/usr/bin/env python3
# Trigrams - Assingment 3
import random
import pathlib
import sys
story_length = 200
def get_file():
source = pathlib.Path.home() / filename
with open(str(source), 'r') as infile:
words = infile.read()
return words
def clean_words(words):
''' The text changes slightly between E-Books so I am just using the raw file
and not parsing out the START and end, this was the code which works for
Sherlock.txt but not other things:
#start_mark = "START OF THE PROJECT GUTENBERG EBOOK"
#end_mark = "END OF THE PROJECT GUTENBERG EBOOK"
#words = words.split(start_mark)
#words = str(words[1])
#words = words.split(end_mark)
#words = str(words[0])
#table = str.maketrans(dict.fromkeys('"!.,'))
#words = words.translate(table)
'''
words = words.replace("'","")
words = words.replace('"',"")
words = words.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): # why -2 ?
pair = words[i:i + 2]
follower = words[i + 2]
tuppair = tuple(pair)
if trigrams.get(tuppair) == None:
trigrams[tuppair] = [follower]
else:
trigrams.get(tuppair).append(follower)
return trigrams
def rand_story(trigrams):
''' Assembles a story from the trigrams,
adjust story length using:
story_length var, 100 words are the default
'''
starter = random.choice(list(trigrams))
print("Seed words ---> ", starter)
nov = list(starter)
for x in range(0,story_length):
try:
nxt = trigrams[(nov[len(nov)-2]),(nov[len(nov)-1])]
except:
break
nov.append(random.choice(nxt))
nov[0] = nov[0].capitalize()
output = " ".join(nov) + "."
return output
if __name__ == "__main__":
try:
filename = sys.argv[1]
except IndexError:
print("You must pass in a filename")
sys.exit(1)
words = get_file()
words = clean_words(words)
trigrams = build_trigrams(words)
output = rand_story(trigrams)
print(output)
|
af2b6378e4b3ff67591869d040fa78a5570035a6 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/allen_maxwell/Lesson_09/cli_main.py | 4,993 | 3.765625 | 4 | #!/usr/bin/env python3
# Allen Maxwell
# Python 210
# 1/20/2020
# cli_main.py
import os
from donor_models import *
def menu():
'''Prompts for a user menu selection'''
while True:
response = input('\n'.join((
'\n',
'Please choose from the following '
'options:',
'1) Create a Report',
'2) Send a Thank You letter to a donor',
'3) Send a Thank You letter to all donors',
'4) Quit',
'Please enter your selection > ')))
message = check_menu_response(response)
if message is not None:
print(message)
def check_menu_response(response):
'''Checks user menu selection'''
try:
menu_dict.get(int(response))()
except TypeError:
return '\nPlease enter a number 1 - 4'
except ValueError:
return '\nPlease enter a number 1 - 4'
def thank_you():
'''Creates a thank you letter for a single donor'''
print()
name = get_donor_name(donors)
donation = get_donation_amount(name)
DonorCollection.add_donation(donors, name, donation)
print(get_letter_text(name, donation))
def get_donor_name(donors):
'''Gets the name of the donor'''
while True:
response = input("Please enter the full name of the donor, 'List' for "
"a list of donors, or 'Quit' to exit to the menu > ")
answer = check_donor_name(response)
if answer == response.title():
return answer
else:
print(answer)
def check_donor_name(response):
'''Checks the donor is in the dict'''
try:
if response.lower() == 'quit':
menu()
elif response.lower() == 'list':
return '\n'.join(sorted(DonorCollection.get_donors_names(donors)))
else:
response.split()[1]
return check_new_donor(response.title())
except IndexError:
return 'Please enter a full name'
def check_new_donor(name):
if donors.is_donor_present(name):
return name
else:
response = input('Donor does not exist on file. Do you want to add {} '
'to the donor list? Y/N : '.format(name))
if response.upper() == 'Y':
return name
else:
return "Please enter another donor's name."
def get_donation_amount(name):
'''Gets the amount of the donation'''
while True:
donation = input("Please enter the amount of the donation for {} or "
"'Quit' to exit to the main menu > $ ".format(name))
if donation.lower() == 'quit':
menu()
donation_float = check_donation_amount(donation)
if (type(donation_float) == float) and (donation_float <= 0):
print('Please enter a positive numeric value, greater than zero')
elif type(donation_float) == float:
return donation_float
else:
print(donation_float)
def check_donation_amount(donation):
'''Checks the donation is a numeric value'''
try:
result = float(donation)
except ValueError:
result = 'Please enter a positive numeric value'
return result
def get_letter_text(name, donation):
'''Formats an email thanking the donor for their donation'''
donor = {'first_name': name.split()[0],
'last_name': name.split()[1].strip(','),
'amount': donation}
letter = '''\n
Dear {first_name} {last_name},\n
Thank you so much for your generous gift of ${amount:,.2f}!\n
Your donation will go far in helping so many orphaned kittens
and puppies find a new home.\n
Thank You,\n
Paws'''.format(**donor)
return letter
def display_report():
'''Prints report to screen'''
print()
header = ('{:<19}{:3}{:12}{:3}{:10}{:3}{:<10}'.format(
'Donor Name', '|',
'Total Given', '|',
'Num Gifts', '|',
'Average Gift'))
header += ('\n' + '-'*62)
print(header)
for donor in DonorCollection.get_report(donors):
print('{:<21}${:>11,.2f}{:^16}${:>11,.2f}'.format(*donor))
def thank_all():
'''Formats and saves a letter thanking all the donor for their donations'''
save_thank_all(donors)
print('\nTask Complete')
def save_thank_all(donors):
'''Saves a letter thanking all the donor to file'''
for donor in donors.donors.values():
Donor.save_donor_file(donor, get_letter_text(donor.name,
donor.total_donations))
def quit():
'''Exit the program'''
print('\nGood Bye!\n\n')
exit()
d1 = Donor('William Gates', [653784.49, 2])
d2 = Donor('Mark Zuckerberg', [16396.10, 3])
d3 = Donor('Jeff Bezos', [877.33, 1])
d4 = Donor('Paul Allen', [708.42, 3])
d5 = Donor('Steve Jobs', [10000.00, 1])
donors = DonorCollection(d1, d2, d3, d4, d5)
menu_dict = {
1: display_report,
2: thank_you,
3: thank_all,
4: quit, }
if __name__ == "__main__":
menu()
|
e4d8d82953f6840898ef0d290c76b7a6ea417c1e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/anthony_mckeever/lesson9/assignment_1/cli_main.py | 3,440 | 3.828125 | 4 | """
Programming In Python - Lesson 9 Assignment 1: Object Oriented Mail Room
Code Poet: Anthony McKeever
Start Date: 09/10/2019
End Date: 09/15/2019
"""
import argparse
import os.path as path
from support import Helpers
from support import FileHelpers
from support import MenuItem
from support import MenuDriven
from donor_models import Donor
from donor_models import Donor_Collection
parser = argparse.ArgumentParser(description="Studio Starchelle's Donor Appreciation System")
parser.add_argument("--donors", metavar="path", help="The donor list to import", type=str,
default=FileHelpers.default_resource_file_path("donor_list.csv"))
parser.add_argument("--email", metavar="path", help="The email template to import", type=str,
default=FileHelpers.default_resource_file_path("email_template.txt"))
donor_list = None
def main(args):
"""
The main method of the applicaiton.
:args: The arguments parsed from argparse
"""
print("\nStudio Starchelle Donor Appreciation System")
main_menu = [
MenuItem("Send a Thank You", "Get email template to thank a donor.", send_thanks),
MenuItem("Create a Report", "View all donors and their cumulative donations",
create_report),
MenuItem("Send Letters to All", "Generate a letter for every donor.", send_to_all)
]
main_menu = MenuDriven("Main Menu:", main_menu, "What do you want to do?")
try:
while True:
main_menu.run_menu()
except SystemExit:
donor_list.save_to_file(args.donors)
raise
def send_thanks():
"""
Accept a donation and thank the donor.
"""
thanks = [MenuItem("List Donors", "Print a list of available donors.",
print_donors, tabs=3)]
thanks = MenuDriven("Lets Send Thanks!", thanks,
"Who would you like to thank? (Enter '1' to list donors)",
show_main=True, invalid=donor_list.handle_donation)
thanks.run_menu()
def print_donors():
"""
Prints a list of donor names.
"""
print(donor_list.get_names)
def create_report():
"""
Print a report of donors, their total donations, count of donations and average donation.
"""
headers = ["Name:", "Total Given:", "Number of Gifts:", "Average Gift:"]
summary = sorted(donor_list, reverse=True)
summary = [d.to_summary for d in summary]
print("\n".join(Helpers.get_table(headers, summary)) + "\n")
def send_to_all():
"""
Export thank you notes for all donors.
"""
print("\n\nLets thank everybody!")
print(str("\nThis will prepare a letter to send to everyone has donated to "
"Studio Starchelle in the past."))
print(str("All letters will be saved as text (.txt) files in the default directory a "
"different directory is specified."))
save_dir = FileHelpers.get_user_output_path()
if save_dir is None:
print("\nCancelling send to all. Returning to main menu...\n")
return
for donor in donor_list:
file_path = path.join(save_dir, f"{donor.name}.txt")
FileHelpers.write_file(file_path, donor.get_email(donor_list.email_template))
print(f"Donor letters successfully saved to: {save_dir}")
if __name__ == "__main__":
args = parser.parse_args()
donor_list = Donor_Collection.from_file(args.donors, args.email)
main(args)
|
6f2f95b70ee56d0a9e75bac0207a2b5f30b263e9 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/cbrown/Lesson 2/Sum_Series.py | 434 | 3.96875 | 4 | #Sum Series Exercise
def sum_series(n,x = 0,y = 1):
'''
returns the nth value of the fibonacci series
'''
#sequence list
fib_seq = [x,y]
#fibonacci series counter
index = 0
if n == 0:
return fib_seq[0]
for i in range(n - 1):
new_fib_num = fib_seq[index] + fib_seq[index+1]
fib_seq.append(new_fib_num)
index = index + 1
return fib_seq[-1]
sum_series(0,3,2)
|
c65f36c96fb3e5f1579b165fb4e52c28bf5efa82 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Isabella_Kemp/lesson03/list_lab.py | 2,349 | 4.46875 | 4 | # Isabella Kemp
# 1/19/2020
# list lab
# Series 1
# Create a list that displays Apples, Pears, Oranges, Peaches and display the list.
List = ["Apples", "Pears", "Oranges", "Peaches"]
print(List)
# Ask user for another fruit, and add it to the end of the list
Question = input("Would you like another fruit? Add it here: ")
if Question not in List:
List.append(Question)
print(List)
# Asks user for a number, and displays the number as well as the fruit corresponding
# to the number.
List = ["Apples", "Pears", "Oranges", "Peaches"]
num = int(input("Please enter a number: "))
print(num)
if num < len(List):
print(List[num - 1])
# Adds new fruit (Strawberries) to the beginning of the original fruit list, using +.
new_list = ["Strawberries"] + List
print(new_list)
# Adds new fruit (Strawberries) to beginning of List using insert()
List = ["Apples", "Pears", "Oranges", "Peaches"]
List.insert(0, "Strawberries")
print(List)
# Display all fruits that begin with "P" using a for loop
List = ["Apples", "Pears", "Oranges", "Peaches"]
for fruit in List:
if "P" in fruit[0]:
print(fruit)
# Series 2
# Display the List
List = ["Apples", "Pears", "Oranges", "Peaches"]
print(List)
# Removes last fruit in the list
List.pop()
print(List)
# Deletes the fruit the user wants you to delete
delete_fruit = input("Which fruit would you like to delete? ")
for fruit in List:
if delete_fruit == fruit:
List.remove(delete_fruit)
break # exits loop
print(List)
# Series 3
# Asks the user what fruit they like, and if they say no it deletes the fruit,
# if neither, it will continue to ask. Puts fruits to lower case.
List = ["Apples", "Pears", "Oranges", "Peaches"]
def find_fav_fruits(List):
for fruit in List:
ask_user = input("Do you like " + fruit.lower() + "? yes/no?")
if ask_user.lower() == "no":
List.remove(fruit)
elif ask_user.lower() == "yes":
continue
else:
ask_user = input("Please enter yes or no.")
print(List)
find_fav_fruits(List)
# Series 4
# Creates a new list with the contents of the original, but all letters in each item reversed.
List = ["Apples", "Pears", "Oranges", "Peaches"]
new_list = [fruit[::-1] for fruit in List][::-1]
print(new_list)
print("Deletes last item of the original list")
List.pop()
print(List)
|
0732cf6caebe20edd686aceb2b45a32995b78451 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/scott_bromley/lesson04/mailroom2.py | 4,888 | 3.5625 | 4 | #!/usr/bin/env python3
import datetime
import statistics
import tempfile
# prompt user to select from mailroom menu: send a thank you, create a report, or quit
# send a thank you: allows user to select a name, adds donor if not in donor list, otherwise ask for donation
# and thanks donor
# create a report summarizes the donors and their donations in a table
# quit ends the program
# donors exists in global namespace
donors = {"David Einhorn": [1800.18, 36036.36], "Mark Zuckerberg": [7272.72, 1818.18, 545454.54],
"Seth Klarman": [180.00, 72.72, 18.00], "Bill Ackerman": [324.32],
"Michael Bloomberg": [363363.63, 18181.81]}
now = datetime.datetime.now()
def main():
main_prompt = ("\nPlease enter an option from the following menu\n"
"1 - Send a Thank You to a single donor\n"
"2 - Create a Report\n"
"3 - Send letters to all donors\n"
"4 - Quit\n>> ")
dispatch = {1: send_thank_you, 2: create_report, 3: send_thank_you_all_donors, 4: quit_mailroom}
menu_selection(main_prompt, dispatch)
def menu_selection(prompt, dispatch_dict):
"""
prompts user for input and calls function object in dispatch_dict
:param prompt: user input prompt
:param dispatch_dict: dict of dispatch functions
:return:
"""
while True:
response = int(get_user_input(f"{prompt}"))
if dispatch_dict[response]() == 4:
break
def quit_mailroom():
"""
quits the mailroom
:return:
"""
return 4
def send_thank_you():
"""
prompts user for a donor name; if name exists, prompts for donation, otherwise adds to donors
list displays a list of donors
generates
:return: None
"""
donor_name = get_user_input("Please enter the name of a donor: > ")
if donor_name == 'list':
print(f"List of donors: {', '.join(k for k, v in donors.items())}")
else:
donation = float(get_user_input("Please enter the donation amount: ").strip('$'))
donor_info = {"first_name": donor_name.strip().split(' ')[0], "last_name": donor_name.strip().split(' ')[1],
"donation_amount": donation}
if donor_name in donors:
donors.setdefault(donor_name, []).append(donation)
else:
print(f"Sorry, the name you entered is not in our donor list. Adding donor to list...")
donors.setdefault(donor_name, []).append(donation)
print(format_thank_you(donor_info))
def send_thank_you_all_donors():
"""
generate a thank you letter for all donors, write each letter to disk as .txt in tempdir
:return: None
"""
with tempfile.TemporaryDirectory(suffix='mailroom2', prefix='tys_all_donors', dir='.') as tempdir:
for donor in donors:
donor_info = {"first_name": donor.strip().split(' ')[0],
"last_name": donor.strip().split(' ')[1],
"donation_amount": format(donors.get(donor)[-1], '.2f')}
with open(f"{donor_info['first_name']}_{donor_info['last_name']}_{now.date()}.txt", 'w') as f:
f.write(format_thank_you(donor_info))
def format_thank_you(donor_info={}):
"""
:param donor_info: dict containing donor first and last name, donation
:return:
"""
thank_you = (
f"\n\n{now.date()}\n\n"
f""
f"Dear {donor_info['first_name']} {donor_info['last_name']},\n\n"
f""
f"On behalf of all of us at the ADL office we'd like to recognize and thank you for your generous\n"
f"donation of ${donor_info['donation_amount']}. "
f"These funds will be used to further our mission in fighting hate\n"
f"through leadership programs and education. \n\n"
f"We look forward to seeing you at this year's banquet.\n"
f"\n"
f"Sincerely, "
f"\n"
f"ADL")
return thank_you
def create_report():
"""
print a formatted table of donors ranked in descending order by Total Given
:return: None
"""
donor_summary = []
for donor in donors:
donor_summary.append([donor, sum(donors.get(donor)), len(donors.get(donor)),
statistics.mean(donors.get(donor))])
donor_summary.sort(key=lambda x: float(x[1]), reverse=True)
print(donor_summary)
print(f"Donor Name{'':<20} | Total Given{'':>0} | Num Gifts{'':>0} | Average Gift{'':>0}")
print(f"-" * 72)
for name, total, num_gift, avg_gift in donor_summary:
print(f"{name:<32}${total:>11.2f}{num_gift:>12} ${avg_gift:>13.2f}")
def get_user_input(prompt):
"""
:param prompt: prompt for user to respond to
:return: response to question/prompt
"""
return input(prompt).strip()
if __name__ == "__main__":
print("Running", __file__)
main()
else:
print("Running %s as imported module", __file__) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.