Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
3888035
started dict labs
Oct 22, 2014
66a38f4
Added, debugged dict problem code
Oct 23, 2014
0524242
Added, debugged first set problem
Oct 23, 2014
875428a
Added, debuged final set problem
Oct 23, 2014
629280d
Added, debugged safe_input version
Oct 24, 2014
55ff3e1
Started file input function
Oct 24, 2014
22aaa7c
Built, tested get_book function
Oct 24, 2014
93fada2
Added, debugged preprocessing functions on input text, started dictio…
Oct 25, 2014
47115e3
Dictionary constructor now working and fixed formatting of trigram_key
Oct 25, 2014
a6940d4
Added random selection of initial key and get_newword function to sel…
Oct 25, 2014
a3c7295
Restored for loops to add in newlines and punctuation at end
Oct 26, 2014
7f7f7e3
Added ellipses at beginning and end of generated text, removed debug …
Oct 26, 2014
a16bd14
Added, debugged pathlib version
Oct 26, 2014
009e152
Removed extra lines and whitespace
Oct 26, 2014
026a4c7
Added copy progam, source file, and target directory
Oct 26, 2014
2824ccb
Added copier and source file
Oct 26, 2014
56d7329
Converted database structure to dict and got all dependent functions …
Oct 26, 2014
3de8ac8
Added, debugged email text file writing function
Oct 26, 2014
85a45f6
Added, debugged dict function for user choice
Oct 26, 2014
11930a3
Added, debugged use of dict and format to make thank you template.
Oct 27, 2014
644610b
Removed debugging lines
Oct 27, 2014
47df8af
Merge branch 'master' of https://github.com/UWPCE-PythonCert/IntroToP…
Oct 29, 2014
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Students/RPerkins/session04/dict_setlab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
__author__ = 'Robert W. Perkins'


d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
print d
d.pop('cake')
print d
d['fruit'] = 'Mango'
print d
print d.keys()
print d.values()
print 'cake' in d
print 'Mango' in d.values()

int_list = []
hex_list = []
for i in range(16):
int_list.append(i)
hex_list.append(hex(i))

h_ex={}
for k, l in zip(int_list, hex_list):
h_ex[k] = l
print h_ex

d_prime = {}
for k, v in d.items():
d_prime[k] = v.count('t')
print d_prime

s2 = set()
s3 = set()
s4 = set()
for k in range(20):
if k % 2 == 0:
s2.update([k])
if k % 3 == 0:
s3.update([k])
if k % 4 == 0:
s4.update([k])
print s2
print s3
print s4
print s3.issubset(s2)
print s4.issubset(s2)

p_set = {'P', 'y', 't', 'h', 'o', 'n'}
p_set.update(['i'])
m_set = frozenset(('m', 'a', 'r', 'a', 't', 'h', 'o', 'n'))
print p_set.union(m_set)
print p_set.intersection(m_set)
7 changes: 7 additions & 0 deletions Students/RPerkins/session04/file_copier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
__author__ = 'Robert W. Perkins'

from_file = './test.txt'
to_file = './test/testcopy.txt'

indata = open(from_file).read()
open(to_file, 'w').write(indata)
84 changes: 84 additions & 0 deletions Students/RPerkins/session04/kata14.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
__author__ = 'Robert W. Perkins'
import random


def get_book(target):
""" Open target file and read contents into book_data"""
f = open(target)
book_data = f.read()
f.close()
return book_data


def strip_newlines(in_text):
""" Replace newlines with spaces"""
return in_text.replace('\n', ' ')


def mk_wordlist(in_list):
"""Split input string at spaces and return word list"""
return in_list.split(' ')


def create_dict(orig_text):
""" Create trigram dictionary"""
trigram = {}
word_list = mk_wordlist(strip_newlines(orig_text))
for idx, word in enumerate(word_list):
if idx > (len(word_list) - 3):
break
else:
trigram_key = '%s %s' % (word_list[idx], word_list[idx + 1])
if trigram_key in trigram:
trigram[trigram_key].append(word_list[idx + 2])
else:
trigram[trigram_key] = [word_list[idx + 2]]
return trigram


def get_randomkey(t_gram):
"""Return a random key"""
return random.choice(list(t_gram.keys()))


def get_newword(word_key, word_dict):
"""Return a random word from the list at the provided key"""
new_wordlist = word_dict.get(word_key)
return random.choice(new_wordlist)


def create_newbook(trigram_dict, word_limit, w_line):
"""Create random output of num_words words, using trigram_dict keys to generate new words"""
start_key = get_randomkey(trigram_dict)
new_word = get_newword(start_key, trigram_dict)
out_list = start_key.split(' ')
out_list.insert(0, '...')
out_list.append(new_word)
left_frame = 0

for i in range(word_limit):
for j in range(w_line):
next_key = '%s %s' % (out_list[left_frame+1], out_list[left_frame + 2])
while not next_key in trigram_dict:
next_key = get_randomkey(trigram_dict)
next_word = get_newword(next_key, trigram_dict)
out_list.append(next_word)
left_frame += 1
out_list.append('\n')
out_list.append('...')
out_string = ' '.join(out_list)
return out_string


if __name__ == '__main__':
# num_words gives the number of words to be generated
# words_line gives the number of words per line
num_words = 200
words_line = 20
#source_text = '/intropython/data/sherlock_small.txt'
source_text = '/intropython/data/sherlock.txt'

new_inbook = get_book(source_text)
new_dict = create_dict(new_inbook)
new_outbook = create_newbook(new_dict, num_words, words_line)
print new_outbook
118 changes: 118 additions & 0 deletions Students/RPerkins/session04/mailroom.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
__author__ = 'Robert W. Perkins'


def mk_dbase():
"""Create data structure for donor list"""
# donor name = key: sum of donations, donation 1, donation 2, ...
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while it makes some sense to store a calculated value, it does mean you need to be careful to keep them in sync. You also might want to use a slightly more complex data structure, so that it's clear that the total is a differnt thing:

maybe:
ndbase = {
'Jeff McCarthy': (4000, [2500, 1000, 500]),

ndbase = {
'Jeff McCarthy': [4000, 2500, 1000, 500],
'Tabitha Simmons': [2450, 450, 2000],
'Angela Cartwright': [5500, 5500],
'Billy Murray': [3700, 3450, 250],
'Alexa Dalton': [6940, 240, 1200, 5500]
}
return ndbase


def get_input():
"""Ask user whether to send thank you note or create report and return answer"""

choices = {
'1': 'Enter "1" to Send a Thank-You Note',
'2': 'Enter "2" to Create a Report',
'q': 'Enter "q" to quit-->'
}
in_put = None
while not in_put in choices:
in_put = raw_input('%s, %s, %s' % (choices['1'], choices['2'], choices['q']))
return in_put


def safe_input():
try:
new_d = raw_input("Enter donation amount (must be numeric)-->")
except EOFError:
return None
except KeyboardInterrupt:
return None
return int(new_d)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what will happen if the input is not an integer?



def print_email(p_name, p_donation):
""" Print thank you note for donation from p_name """
ltr_temp = {'Template1': 'Dear {name}, Thanks so much for your generous donation of ${donation}. '
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why put this in a dict? are you anticipating being able to chose more than one template?

'It is greatly appreciated!'
}

print ltr_temp['Template1'].format(name=p_name, donation=p_donation)


def app_record(app_name, app_dict):
""" Append an existing donor record """
app_donation = safe_input()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what will happen if safe_input returns None?

app_dict[app_name].append(app_donation)
app_dict[app_name][0] += app_donation
print_email(app_name, app_donation)


def add_record(add_name, add_dict):
""" Add new donor to database """
add_donation = safe_input()
add_dict[add_name] = [add_donation, add_donation]
print_email(add_name, add_donation)


def thank_you(donor_dict):
""" Find or create a donor, add new donation, and return a thank you note"""
name = 'list'
while name == 'list':
new_name = raw_input("Enter full name of donor-->")
name = str(new_name)
if not (name == 'list'):
break
else:
for item in donor_dict:
print item

if name in donor_dict:
app_record(name, donor_dict)
else:
add_record(name, donor_dict)


def write_efile(name, donation_list):
"""write a donor email to disk named "name".txt"""
to_file = './%s.txt' % name
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the "./" is assumed anyway.

outdata = 'Dear %s, Thanks so much for your recent generous donation of $%s. ' \
'It is greatly appreciated!' % (name, donation_list[-1])
open(to_file, 'w').write(outdata)


#def sum_element(key_dbase):
#"""set key for sorting on sum element of data structure"""
#return key_dbase[1]


def mk_report(rep_dict):
""" Create a sorted list of donors"""
print 'Donor Name\t\t\tTotal Donations\t# of Donations\t\tAverage Donation'
#rep_dbase.sort(key=sum_element)
for j, k in rep_dict.items():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how could you sort this?

num_donations = len(k)-1
avg_donation = k[0]/(len(k)-1)
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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tabs are tricky -- different terminals, etc will expand them differently.

better to use spaces -- and you can use the formatters to align it all for you.

write_efile(j,k)


if __name__ == '__main__':
donor = mk_dbase()
answer = None
while not (answer == "q"):
answer = get_input()
if answer == "q":
break
elif answer == "1":
thank_you(donor)
else:
mk_report(donor)
print "Exiting"
7 changes: 7 additions & 0 deletions Students/RPerkins/session04/print_filepath.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
__author__ = 'Robert W. Perkins'

import pathlib

pth = pathlib.Path('./')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice! pathlib is pretty cool, eh?

for f in pth.iterdir():
print '%s\%s' % (pth.absolute(), f)
1 change: 1 addition & 0 deletions Students/RPerkins/session04/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This is the test file content
1 change: 1 addition & 0 deletions Students/RPerkins/session04/test/testcopy.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This is the test file content
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably a good idea for you test file to be more than one line, just in case...