Skip to content
This repository was archived by the owner on Jun 9, 2021. It is now read-only.

Commit 9613ba8

Browse files
committed
2 parents 79d8b2e + 6856bc9 commit 9613ba8

File tree

25 files changed

+14408
-22
lines changed

25 files changed

+14408
-22
lines changed

materials/source/notes/session05.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ similarly:
6767

6868
``for k in dict:``
6969

70-
loops through the keys. So need for:
70+
loops through the keys. So no need for:
7171

7272
``for k in dict.keys():``
7373

materials/source/notes/session06.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,61 @@ A collection of notes to go over in class, to keep things organized.
1212
Lightning Talks
1313
===============
1414

15+
Marlon M Estrada
16+
17+
Ali Dehghani
18+
1519
Alinafe Matenda
1620

1721
Daniel W Kuchan
1822

1923
Kathryn Egan
2024

25+
Feedback
26+
========
27+
28+
We got the results of the feedback survey last week.
29+
30+
We really do read the comments and try to improve the class as we go.
31+
32+
So Thanks!
33+
34+
And you'll get another chance at the end of class, which we also appreciate.
35+
2136

2237
Issues that came up during the week.
2338
====================================
2439

40+
Getting an arbitrary key from a dict
41+
------------------------------------
42+
43+
See ``arbitrary_key.py`` in `solutions/session04`
44+
45+
dict as switch -- how do you leave the loop?
46+
--------------------------------------------
47+
48+
Let's look at Eowyn's solution...
49+
50+
51+
globals??
52+
---------
53+
54+
a number of you have been putting code in the global (module) namespace:
55+
56+
.. code-block:: python
57+
58+
the_dict = {}
59+
60+
def fun():
61+
...
62+
the_dict = something()
63+
64+
What's wrong with this?
65+
66+
More on keyword arguments:
67+
--------------------------
68+
69+
:ref:`keyword_only_arguments`
70+
71+
72+

solutions/Session04/mailroom2.py

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def get_donor_db():
3030

3131
def list_donors():
3232
"""
33-
creates a list of the donors as a string, so they can be printed
33+
Create a list of the donors as a string, so they can be printed
3434
3535
Not calling print from here makes it more flexible and easier to
3636
test
@@ -43,10 +43,9 @@ def list_donors():
4343

4444
def find_donor(name):
4545
"""
46-
find a donor in the donor db
46+
Find a donor in the donor db
4747
4848
:param: the name of the donor
49-
5049
:returns: The donor data structure -- None if not in the donor_db
5150
"""
5251
key = name.strip().lower()
@@ -58,7 +57,6 @@ def add_donor(name):
5857
Add a new donor to the donor db
5958
6059
:param: the name of the donor
61-
6260
:returns: the new Donor data structure
6361
"""
6462
name = name.strip()
@@ -88,7 +86,6 @@ def gen_letter(donor):
8886
Generate a thank you letter for the donor
8987
9088
:param: donor tuple
91-
9289
:returns: string with letter
9390
9491
note: This doesn't actually write to a file -- that's a separate
@@ -104,22 +101,10 @@ def gen_letter(donor):
104101
'''.format(donor[0], donor[1][-1]))
105102

106103

107-
def send_thank_you():
104+
def take_donation(name):
108105
"""
109-
Execute the logic to record a donation and generate a thank you message.
106+
Ask user for donation amount, and then add it to the DB
110107
"""
111-
# Read a valid donor to send a thank you from, handling special commands to
112-
# let the user navigate as defined.
113-
while True:
114-
name = input("Enter a donor's name (or list to see all donors or "
115-
"'menu' to exit)> ").strip()
116-
if name == "list":
117-
print(list_donors())
118-
elif name == "menu":
119-
return
120-
else:
121-
break
122-
123108
# Now prompt the user for a donation amount to apply. Since this is
124109
# also an exit point to the main menu, we want to make sure this is
125110
# done before mutating the db.
@@ -149,9 +134,27 @@ def send_thank_you():
149134

150135
# Record the donation
151136
donor[1].append(amount)
137+
# print the thank you letter
152138
print(gen_letter(donor))
153139

154140

141+
def send_thank_you():
142+
"""
143+
Execute the logic to record a donation and generate a thank you message.
144+
"""
145+
# Read a valid donor to send a thank you from, handling special commands to
146+
# let the user navigate as defined.
147+
while True:
148+
name = input("Enter a donor's name or 'list' to see all donors or "
149+
"'menu' to exit to main menu > ").strip()
150+
if name == "list":
151+
print(list_donors())
152+
elif name == "menu":
153+
return
154+
else:
155+
take_donation(name)
156+
157+
155158
def sort_key(item):
156159
# used to sort on name in donor_db
157160
return item[1]
@@ -192,6 +195,7 @@ def save_letters_to_disk():
192195
letter = gen_letter(donor)
193196
# I don't like spaces in filenames...
194197
filename = donor[0].replace(" ", "_") + ".txt"
198+
print("writting letter to:", donor[0])
195199
open(filename, 'w').write(letter)
196200

197201

@@ -200,15 +204,19 @@ def print_donor_report():
200204

201205

202206
def quit():
207+
"""
208+
quit the program
209+
210+
Note: you could put the sys.exit call directly in the dict
211+
but this lets you put extra code in there if you want.
212+
"""
203213
sys.exit(0)
204214

205215

206216
if __name__ == "__main__":
207217

208218
donor_db = get_donor_db()
209219

210-
running = True
211-
212220
selection_dict = {"1": send_thank_you,
213221
"2": print_donor_report,
214222
"3": save_letters_to_disk,
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
dict/set lab solutions: Chris' version.
5+
6+
This time with comprehensions:
7+
"""
8+
9+
food_prefs = {"name": "Chris",
10+
"city": "Seattle",
11+
"cake": "chocolate",
12+
"fruit": "mango",
13+
"salad": "greek",
14+
"pasta": "lasagna"}
15+
16+
# 1. Print the dict by passing it to a string format method, so that you
17+
# get something like:
18+
19+
print("{name} is from Seattle, and he likes {cake} cake, {fruit} fruit,"
20+
"{salad} salad, and {pasta} pasta".format(**food_prefs))
21+
22+
# 2. Using a list comprehension, build a dictionary of numbers from zero
23+
# to fifteen and the hexadecimal equivalent (string is fine).
24+
25+
print(dict([(i, hex(i)) for i in range(16)]))
26+
27+
# 3. Do the previous entirely with a dict comprehension -- should be a one-liner
28+
29+
print({i: hex(i) for i in range(16)})
30+
31+
# 4. Using the dictionary from item 1: Make a dictionary using the same
32+
# keys but with the number of 'a's in each value. You can do this either
33+
# by editing the dict in place, or making a new one. If you edit in place,
34+
# make a copy first!
35+
36+
print({key: val.count('a') for key, val in food_prefs.items()})
37+
38+
39+
# 5. Create sets s2, s3 and s4 that contain numbers from zero through twenty,
40+
# divisible 2, 3 and 4.
41+
42+
# a. Do this with one set comprehension for each set.
43+
s2 = {i for i in range(21) if not i % 2}
44+
s3 = {i for i in range(21) if not i % 3}
45+
s4 = {i for i in range(21) if not i % 4}
46+
47+
48+
print("\nHere are the three sets:")
49+
print(s2)
50+
print(s3)
51+
print(s4)
52+
53+
# b. What if you had a lot more than 3? -- Don't Repeat Yourself (DRY)
54+
# - create a sequence that holds all three sets
55+
# - loop through that sequence to build the sets up -- so no repeated code.
56+
57+
n = 5
58+
divisors = range(2, n + 1)
59+
# create a list of empty sets
60+
sets = [set() for i in divisors]
61+
62+
# fill up the sets
63+
for i, st in zip(divisors, sets):
64+
[st.add(j) for j in range(21) if not j % i]
65+
66+
print("\nHere are all the sets:\n", sets)
67+
68+
69+
# c. Extra credit: do it all as a one-liner by nesting a set comprehension
70+
# inside a list comprehension. (OK, that may be getting carried away!)
71+
72+
sets = [{i for i in range(21) if not i % j} for j in range(2, n + 1)]
73+
74+
print("\nHere are all the sets from the one liner:\n", sets)
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#!/usr/bin/python
2+
3+
"""
4+
An exercise in playing with Exceptions.
5+
Make lots of try/except blocks for fun and profit.
6+
Please remember to catch specifically the error you find,
7+
and not all errors.
8+
"""
9+
10+
from except_test import fun, more_fun, last_fun
11+
12+
13+
# Figure out what the exception is, catch it and while still
14+
# in that catch block, try again with the second item in the list
15+
first_try = ['spam', 'cheese', 'mr death']
16+
17+
try:
18+
joke = fun(first_try[0])
19+
except NameError:
20+
print("Whoops! there is no joke for: {}".format(first_try[0]))
21+
22+
# Here is a try/except block. Add an else that prints not_joke
23+
try:
24+
not_joke = fun(first_try[2])
25+
except SyntaxError:
26+
print('Run Away!')
27+
else:
28+
print(not_joke)
29+
30+
# What did that do? You can think of else in this context, as well
31+
# as in loops as meaning: else if nothing went wrong.
32+
# (no breaks in loops, no exceptions in try blocks)
33+
34+
# Figure out what the exception is, catch it and in that same block
35+
# try calling the more_fun function with the 2nd language
36+
# in the list, again assigning it to next_joke.
37+
38+
# If there are no exceptions, call the more_fun
39+
# function with the last language in the list
40+
# Regardless of whether there was an exception
41+
42+
# Finally, while still in the try/except block
43+
# and regardless of whether there were any exceptions,
44+
# call the function last_fun with no parameters. (pun intended)
45+
46+
langs = ['java', 'c', 'python']
47+
try:
48+
more_joke = more_fun(langs[0])
49+
except IndexError:
50+
more_joke = more_fun(langs[1])
51+
else:
52+
more_joke = more_fun(langs[-1])
53+
finally:
54+
last_fun()

solutions/Session05/except_test.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
silly little test module that is designed to trigger Exceptions when
5+
run from the except_exercise.py file
6+
"""
7+
8+
import time
9+
10+
conclude = "And what leads you to that conclusion?"
11+
district = "Finest in the district, sir."
12+
cheese = "It's certainly uncontaminated by cheese."
13+
clean = "Well, it's so clean."
14+
shop = "Not much of a cheese shop really, is it?"
15+
cust = "Customer: "
16+
clerk = "Shopkeeper: "
17+
18+
19+
def fun(reaper):
20+
if reaper == 'spam':
21+
print(s)
22+
elif reaper == 'cheese':
23+
print()
24+
print('Spam, Spam, Spam, Spam, Beautiful Spam')
25+
elif reaper == 'mr death':
26+
print()
27+
return('{}{}\n{}{}'.format(cust, shop, clerk, district))
28+
29+
30+
def more_fun(language):
31+
if language == 'java':
32+
test = [1, 2, 3]
33+
test[5] = language
34+
elif language == 'c':
35+
print('{}{}\n{}{}'.format(cust, conclude, clerk, clean))
36+
37+
38+
def last_fun():
39+
print(cust, cheese)
40+
time.sleep(1)
41+
import antigravity
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#!/usr/bin/env python3
2+
3+
4+
fb = [[str(i), 'Fizz', 'Buzz', 'FizzBuzz'][(i % 3 == 0) + 2 * (i % 5 == 0)] for i in range(1, 101)]
5+
6+
print('\n'.join(fb))

0 commit comments

Comments
 (0)