Skip to content

Commit 46ce6ea

Browse files
committed
Merge pull request UWPCE-PythonCert#51 from meshmote/master
Added session04 homework
2 parents 2964b02 + 47df8af commit 46ce6ea

File tree

7 files changed

+269
-0
lines changed

7 files changed

+269
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
__author__ = 'Robert W. Perkins'
2+
3+
4+
d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
5+
print d
6+
d.pop('cake')
7+
print d
8+
d['fruit'] = 'Mango'
9+
print d
10+
print d.keys()
11+
print d.values()
12+
print 'cake' in d
13+
print 'Mango' in d.values()
14+
15+
int_list = []
16+
hex_list = []
17+
for i in range(16):
18+
int_list.append(i)
19+
hex_list.append(hex(i))
20+
21+
h_ex={}
22+
for k, l in zip(int_list, hex_list):
23+
h_ex[k] = l
24+
print h_ex
25+
26+
d_prime = {}
27+
for k, v in d.items():
28+
d_prime[k] = v.count('t')
29+
print d_prime
30+
31+
s2 = set()
32+
s3 = set()
33+
s4 = set()
34+
for k in range(20):
35+
if k % 2 == 0:
36+
s2.update([k])
37+
if k % 3 == 0:
38+
s3.update([k])
39+
if k % 4 == 0:
40+
s4.update([k])
41+
print s2
42+
print s3
43+
print s4
44+
print s3.issubset(s2)
45+
print s4.issubset(s2)
46+
47+
p_set = {'P', 'y', 't', 'h', 'o', 'n'}
48+
p_set.update(['i'])
49+
m_set = frozenset(('m', 'a', 'r', 'a', 't', 'h', 'o', 'n'))
50+
print p_set.union(m_set)
51+
print p_set.intersection(m_set)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
__author__ = 'Robert W. Perkins'
2+
3+
from_file = './test.txt'
4+
to_file = './test/testcopy.txt'
5+
6+
indata = open(from_file).read()
7+
open(to_file, 'w').write(indata)
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
__author__ = 'Robert W. Perkins'
2+
import random
3+
4+
5+
def get_book(target):
6+
""" Open target file and read contents into book_data"""
7+
f = open(target)
8+
book_data = f.read()
9+
f.close()
10+
return book_data
11+
12+
13+
def strip_newlines(in_text):
14+
""" Replace newlines with spaces"""
15+
return in_text.replace('\n', ' ')
16+
17+
18+
def mk_wordlist(in_list):
19+
"""Split input string at spaces and return word list"""
20+
return in_list.split(' ')
21+
22+
23+
def create_dict(orig_text):
24+
""" Create trigram dictionary"""
25+
trigram = {}
26+
word_list = mk_wordlist(strip_newlines(orig_text))
27+
for idx, word in enumerate(word_list):
28+
if idx > (len(word_list) - 3):
29+
break
30+
else:
31+
trigram_key = '%s %s' % (word_list[idx], word_list[idx + 1])
32+
if trigram_key in trigram:
33+
trigram[trigram_key].append(word_list[idx + 2])
34+
else:
35+
trigram[trigram_key] = [word_list[idx + 2]]
36+
return trigram
37+
38+
39+
def get_randomkey(t_gram):
40+
"""Return a random key"""
41+
return random.choice(list(t_gram.keys()))
42+
43+
44+
def get_newword(word_key, word_dict):
45+
"""Return a random word from the list at the provided key"""
46+
new_wordlist = word_dict.get(word_key)
47+
return random.choice(new_wordlist)
48+
49+
50+
def create_newbook(trigram_dict, word_limit, w_line):
51+
"""Create random output of num_words words, using trigram_dict keys to generate new words"""
52+
start_key = get_randomkey(trigram_dict)
53+
new_word = get_newword(start_key, trigram_dict)
54+
out_list = start_key.split(' ')
55+
out_list.insert(0, '...')
56+
out_list.append(new_word)
57+
left_frame = 0
58+
59+
for i in range(word_limit):
60+
for j in range(w_line):
61+
next_key = '%s %s' % (out_list[left_frame+1], out_list[left_frame + 2])
62+
while not next_key in trigram_dict:
63+
next_key = get_randomkey(trigram_dict)
64+
next_word = get_newword(next_key, trigram_dict)
65+
out_list.append(next_word)
66+
left_frame += 1
67+
out_list.append('\n')
68+
out_list.append('...')
69+
out_string = ' '.join(out_list)
70+
return out_string
71+
72+
73+
if __name__ == '__main__':
74+
# num_words gives the number of words to be generated
75+
# words_line gives the number of words per line
76+
num_words = 200
77+
words_line = 20
78+
#source_text = '/intropython/data/sherlock_small.txt'
79+
source_text = '/intropython/data/sherlock.txt'
80+
81+
new_inbook = get_book(source_text)
82+
new_dict = create_dict(new_inbook)
83+
new_outbook = create_newbook(new_dict, num_words, words_line)
84+
print new_outbook
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
__author__ = 'Robert W. Perkins'
2+
3+
4+
def mk_dbase():
5+
"""Create data structure for donor list"""
6+
# donor name = key: sum of donations, donation 1, donation 2, ...
7+
ndbase = {
8+
'Jeff McCarthy': [4000, 2500, 1000, 500],
9+
'Tabitha Simmons': [2450, 450, 2000],
10+
'Angela Cartwright': [5500, 5500],
11+
'Billy Murray': [3700, 3450, 250],
12+
'Alexa Dalton': [6940, 240, 1200, 5500]
13+
}
14+
return ndbase
15+
16+
17+
def get_input():
18+
"""Ask user whether to send thank you note or create report and return answer"""
19+
20+
choices = {
21+
'1': 'Enter "1" to Send a Thank-You Note',
22+
'2': 'Enter "2" to Create a Report',
23+
'q': 'Enter "q" to quit-->'
24+
}
25+
in_put = None
26+
while not in_put in choices:
27+
in_put = raw_input('%s, %s, %s' % (choices['1'], choices['2'], choices['q']))
28+
return in_put
29+
30+
31+
def safe_input():
32+
try:
33+
new_d = raw_input("Enter donation amount (must be numeric)-->")
34+
except EOFError:
35+
return None
36+
except KeyboardInterrupt:
37+
return None
38+
return int(new_d)
39+
40+
41+
def print_email(p_name, p_donation):
42+
""" Print thank you note for donation from p_name """
43+
ltr_temp = {'Template1': 'Dear {name}, Thanks so much for your generous donation of ${donation}. '
44+
'It is greatly appreciated!'
45+
}
46+
47+
print ltr_temp['Template1'].format(name=p_name, donation=p_donation)
48+
49+
50+
def app_record(app_name, app_dict):
51+
""" Append an existing donor record """
52+
app_donation = safe_input()
53+
app_dict[app_name].append(app_donation)
54+
app_dict[app_name][0] += app_donation
55+
print_email(app_name, app_donation)
56+
57+
58+
def add_record(add_name, add_dict):
59+
""" Add new donor to database """
60+
add_donation = safe_input()
61+
add_dict[add_name] = [add_donation, add_donation]
62+
print_email(add_name, add_donation)
63+
64+
65+
def thank_you(donor_dict):
66+
""" Find or create a donor, add new donation, and return a thank you note"""
67+
name = 'list'
68+
while name == 'list':
69+
new_name = raw_input("Enter full name of donor-->")
70+
name = str(new_name)
71+
if not (name == 'list'):
72+
break
73+
else:
74+
for item in donor_dict:
75+
print item
76+
77+
if name in donor_dict:
78+
app_record(name, donor_dict)
79+
else:
80+
add_record(name, donor_dict)
81+
82+
83+
def write_efile(name, donation_list):
84+
"""write a donor email to disk named "name".txt"""
85+
to_file = './%s.txt' % name
86+
outdata = 'Dear %s, Thanks so much for your recent generous donation of $%s. ' \
87+
'It is greatly appreciated!' % (name, donation_list[-1])
88+
open(to_file, 'w').write(outdata)
89+
90+
91+
#def sum_element(key_dbase):
92+
#"""set key for sorting on sum element of data structure"""
93+
#return key_dbase[1]
94+
95+
96+
def mk_report(rep_dict):
97+
""" Create a sorted list of donors"""
98+
print 'Donor Name\t\t\tTotal Donations\t# of Donations\t\tAverage Donation'
99+
#rep_dbase.sort(key=sum_element)
100+
for j, k in rep_dict.items():
101+
num_donations = len(k)-1
102+
avg_donation = k[0]/(len(k)-1)
103+
print '%s\t\t\t%s\t\t\t\t%s\t\t\t\t\t\t%s' % (j, k[0], num_donations, avg_donation)
104+
write_efile(j,k)
105+
106+
107+
if __name__ == '__main__':
108+
donor = mk_dbase()
109+
answer = None
110+
while not (answer == "q"):
111+
answer = get_input()
112+
if answer == "q":
113+
break
114+
elif answer == "1":
115+
thank_you(donor)
116+
else:
117+
mk_report(donor)
118+
print "Exiting"
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
__author__ = 'Robert W. Perkins'
2+
3+
import pathlib
4+
5+
pth = pathlib.Path('./')
6+
for f in pth.iterdir():
7+
print '%s\%s' % (pth.absolute(), f)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This is the test file content
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This is the test file content

0 commit comments

Comments
 (0)