forked from barbarer/py4e-int
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathwritecode.ptx
More file actions
463 lines (380 loc) · 20.2 KB
/
writecode.ptx
File metadata and controls
463 lines (380 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
<?xml version="1.0"?>
<section xml:id="dictionaries_write-code-questions">
<title>Write Code Questions</title>
<exercise>
<statement>
<p>Write a program that categorizes each mail message by which day of the week
the commit was done. To do this, look for lines that start with <q>From</q>. Then,
look for the third word, and keep a running count of each of the days of the week.
At the end of the program, print out the contents of the dictionary <c>mail_count</c>
(order does not matter). For example, <c>mail_count['Mon']</c> should be <c>2</c>.</p>
</statement>
<program interactive="activecode" language="python" xml:id="dict_writecode1q_editor">
<input>
mail = ['From stephen.marquard@uct.ac.za Sat Jan 7', 'From gopal.ramasammycook@gmail.com Thurs Jan 5', 'From louis@media.berkeley.edu Tues Jan 3', 'From antranig@caret.cam.ac.uk Sat Jan 7', 'From david.horwitz@uct.ac.za Wed Jan 4', 'From ray@media.berkeley.edu Mon Jan 2', 'From stephen.marquard@uct.ac.za Mon Jan 2', 'From wagnermr@iupui.edu Fri Jan 6']
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(mail_count['Mon'], 2, "mail_count['Mon']")
self.assertEqual(mail_count['Sat'], 2, "mail_count['Sat']")
self.assertEqual(mail_count.get('Sun', 0), 0, "mail_count.get('Sun', 0)")
myTests().main()
</input>
</program>
<solution>
Write a program that categorizes each mail message by which day of the week
the commit was done. To do this, look for lines that start with <q>From</q>. Then,
look for the third word, and keep a running count of each of the days of the week.
At the end of the program, print out the contents of the dictionary mail_count
(order does not matter). For example, mail_count['Mon'] should be 2.
<program xml:id="dict_writecode1a_editor" language="python"><input>
# mail list was given
mail = ['From stephen.marquard@uct.ac.za Sat Jan 7', 'From gopal.ramasammycook@gmail.com Thurs Jan 5', 'From louis@media.berkeley.edu Tues Jan 3', 'From antranig@caret.cam.ac.uk Sat Jan 7', 'From david.horwitz@uct.ac.za Wed Jan 4', 'From ray@media.berkeley.edu Mon Jan 2', 'From stephen.marquard@uct.ac.za Mon Jan 2', 'From wagnermr@iupui.edu Fri Jan 6']
# Create dictionary for the emails
mail_count = {}
# Iterate through each email in the list
for email in mail:
# Separate pieces of each email setting key to the day (third element)
key = email.split()[2]
# Add key to dictionary if not included
if key not in mail_count.keys():
mail_count[key] = 0
# Update key
mail_count[key] += 1
# Print final count
print(mail_count)
</input></program>
</solution>
</exercise>
<exercise label="dict_writecode2">
<statement>
<p>Write a program to read through a mail log, build the dictionary <c>user_count</c> to count how many messages have come from each email address, and print the dictionary. For example, <c>user_count['stephen.marquard@uct.ac.za']</c> should be <c>4</c>.</p>
</statement>
<program xml:id="dict_writecode2_editor" interactive="activecode" language="python">
<input>
mail_log = ['From stephen.marquard@uct.ac.za Sat Jan 7', 'From gopal.ramasammycook@gmail.com Thurs Jan 5', 'From stephen.marquard@uct.ac.za Sat Feb 7', 'From louis@media.berkeley.edu Tues Jan 3', 'From stephen.marquard@uct.ac.za Sat Nov 6', 'From antranig@caret.cam.ac.uk Sat Jan 7', 'From david.horwitz@uct.ac.za Wed Jan 4', 'From ray@media.berkeley.edu Mon Jan 2', 'From stephen.marquard@uct.ac.za Mon Jan 2', 'From wagnermr@iupui.edu Fri Jan 6', 'From gopal.ramasammycook@gmail.com Thurs Dec 5', 'From louis@media.berkeley.edu Tues April 1']
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(len(user_count), 7, "len(user_count)")
self.assertEqual(user_count['stephen.marquard@uct.ac.za'], 4, "user_count['stephen.marquard@uct.ac.za']")
myTests().main()
</input>
</program>
</exercise>
<exercise>
<statement>
<p>Write a program that creates a dictionary <c>letter_count</c> that keeps track
of the amount of times each letter appears in the given phrase. Assign the
number of times <q>e</q> appears in the phrase to the variable <c>e_counter</c>. Make
sure to account for each letter in its lowercase form. For example, <c>e_counter</c> should be <c>10</c>, and <c>letter_count['e']</c> should be <c>10</c>.</p>
</statement>
<program interactive="activecode" language="python" xml:id="dict_writecode3q_editor">
<input>
phrase = "Exeggcute evolves into Exeggutor which are two extraordinary Pokemon"
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(len(letter_count), 21, "len(letter_count)")
self.assertEqual(e_counter, 10, "e_counter")
self.assertEqual(letter_count['e'], 10, "letter_count['e']")
myTests().main()
</input>
</program>
<solution>
Write a program that creates a dictionary letter_count that keeps track
of the amount of times each letter appears in the given phrase. Assign the
number of times <q>e</q> appears in the phrase to the variable e_counter. Make
sure to account for each letter in its lowercase form. For example, e_counter should be 10, and letter_count['e'] should be 10.
<program xml:id="dict_writecode3a_editor" language="python"><input>
# phrase string is given
phrase = "Exeggcute evolves into Exeggutor which are two extraordinary Pokemon"
# Create dictionary for letters and their counts
letter_count = {}
# Iterate through words in string
for word in phrase.split():
# Iterate through each letter
for letter in word:
# Put each letter into lowercase
letter = letter.lower()
# Add letter as key to dictionary, if not included
if letter not in letter_count.keys():
letter_count[letter] = 0
# Update letter
letter_count[letter] += 1
# Create e_counter to see how many are in the phrase
e_counter = letter_count['e']
</input></program>
</solution>
</exercise>
<exercise label="dict_writecode4">
<statement>
<p>Write a program that reads the words in the string <c>phrase</c> and counts how many times each word appears.
Store the words as keys in the dictionary <c>word_dictionary</c>, and then use the in operator as a fast way to
check whether the string is in the dictionary. For example, <c>word_dictionary['Writing']</c> should be <c>1</c>. (Note: ‘Writing' and ‘writing' would be counted as two separate words for this question.)</p>
</statement>
<program xml:id="dict_writecode4_editor" interactive="activecode" language="python">
<input>
phrase = "Writing programs or programming is a very creative and rewarding activity You can write programs for many reasons ranging from making your living to solving a difficult data analysis problem to having fun to helping someone else solve a problem This book assumes that {\em everyone} needs to know how to program and that once you know how to program, you will figure out what you want to do with your newfound skills"
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(len(word_dictionary), 56, "len(word_dictionary)")
self.assertEqual(word_dictionary['Writing'], 1, "word_dictionary['Writing']")
self.assertEqual(word_dictionary['a'], 3, "word_dictionary['a']")
myTests().main()
</input>
</program>
</exercise>
<!--</p>-->
<hint>
<pre>Writing programs or programming is a very creative
and rewarding activity You can write programs for
many reasons ranging from making your living to solving
a difficult data analysis problem to having fun to helping
someone else solve a problem This book assumes that
{\em everyone} needs to know how to program and that once
you know how to program, you will figure out what you want
to do with your newfound skills
We are surrounded in our daily lives with computers ranging
from laptops to cell phones We can think of these computers
as our personal assistants who can take care of many things
on our behalf The hardware in our current-day computers
is essentially built to continuously ask us the question
What would you like me to do next
Our computers are fast and have vasts amounts of memory and
could be very helpful to us if we only knew the language to
speak to explain to the computer what we would like it to
do next If we knew this language we could tell the
computer to do tasks on our behalf that were reptitive
Interestingly, the kinds of things computers can do best
are often the kinds of things that we humans find boring
and mind-numbing</pre>
</hint>
<exercise>
<statement>
<p>Write code that reads in the text from the file words.txt and uses
the dictionary <c>word_count</c> to count the amount of times a word appears
in the file. Watch out for repetition using the .lower() function. For example, <c>word_count['and']</c> should be <c>5</c>.</p>
</statement>
<program interactive="activecode" language="python" xml:id="dict_writecode5q_editor">
<input>
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(len(word_count), 119, "len(word_count)")
self.assertEqual(word_count['and'], 5, "word_count['and']")
self.assertEqual(word_count['what'], 3, "word_count['what']")
myTests().main()
</input>
</program>
<solution>
Write code that reads in the text from the file words.txt and uses
the dictionary word_count to count the amount of times a word appears
in the file. Watch out for repetition using the .lower() function. For example, word_count['and'] should be 5.
<program xml:id="dict_writecode5a_editor" language="python"><input>
# Open the file in "read" mode
with open("words.txt", "r") as filename:
# Create dictionary to count words
word_count = {}
# Separate lines and iterate through them
lines = filename.readlines()
for line in lines:
# Iterate through each word
for word in line.split():
# Set each word to lowercase
word = word.lower()
# Add word to dictionary if not included
if word not in word_count.keys():
word_count[word] = 0
# Update word
word_count[word] += 1
# Print final count
print(word_count)
</input></program>
</solution>
</exercise>
<exercise label="dict_writecode6">
<statement>
<p>Write a program that reads the words in the string <c>phrase</c> and counts how many times each word appears.
Store the words as keys in the dictionary <c>word_dictionary</c>, and then use the in operator as a fast way to
check whether the string is in the dictionary. Make sure to turn all letters in words into lowercase letters in order to avoid any repetition.
For example, <c>word_dictionary.get('Writing', 0)</c> should be <c>0</c>, and <c>word_dictionary['writing']</c> should be <c>1</c>.</p>
</statement>
<program xml:id="dict_writecode6_editor" interactive="activecode" language="python">
<input>
phrase = "Writing programs or programming is a very creative and rewarding activity You can write programs for many reasons ranging from making your living to solving a difficult data analysis problem to having fun to helping someone else solve a problem This book assumes that {\em everyone} needs to know how to program and that once you know how to program, you will figure out what you want to do with your newfound skills"
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(len(word_dictionary), 55, "len(word_dictionary)")
self.assertEqual(word_dictionary['you'], 4, "word_dictionary['you']")
self.assertEqual(word_dictionary['writing'], 1, "word_dictionary['writing']")
self.assertEqual(word_dictionary.get('Writing', 0), 0, "word_dictionary.get('Writing', 0)")
myTests().main()
</input>
</program>
</exercise>
<p>Below is the romeo3.txt file used in Question 7.</p>
<hint>
<pre>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief</pre>
</hint>
<exercise>
<statement>
<p>Write code to read through the lines of the file, break each line into a list of
words, and then loop through each of the words in the line and count each word using
the dictionary <c>counts</c>. For example, <c>counts['is']</c> should be <c>3</c>.</p>
</statement>
<program interactive="activecode" language="python" xml:id="dict_writecode7q_editor">
<input>
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(len(counts), 26, "len(counts)")
self.assertEqual(counts['is'], 3, "counts['is']")
self.assertEqual(counts['arise'], 1, "counts['arise']")
myTests().main()
</input>
</program>
<solution>
Write code to read through the lines of the file, break each line into a list of
words, and then loop through each of the words in the line and count each word using
the dictionary counts. For example, counts['is'] should be 3.
<program xml:id="dict_writecode7a_editor" language="python"><input>
# Open file in "read" mode
with open("romeo.txt", "r") as filename:
# Separate and read lines
lines = filename.readlines()
# Create count dictionary
counts = {}
# Iterate through lines
for line in lines:
# Iterate through words in each line
for word in line.split():
# Set each word to lowercase
word = word.lower()
# Add word to dictionary if not included
if word not in counts.keys():
counts[word] = 0
# Update word
counts[word] += 1
</input></program>
</solution>
</exercise>
<exercise label="dict_writecode8">
<statement>
<p>Write code that adds the key ‘two' with a value of ‘dos' to the dictionary <c>eng2sp</c>. For example, <c>eng2sp['two']</c> should be <c>'dos'</c>.</p>
</statement>
<program xml:id="dict_writecode8_editor" interactive="activecode" language="python">
<input>
eng2sp = {'one':'uno'}
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(eng2sp['two'], 'dos', "eng2sp['two']")
myTests().main()
</input>
</program>
</exercise>
<p>The next two questions are associated with the following text file which has an email address followed by the number of messages from that address.</p>
<hint>
<pre>gopal.ramasammycook@gmail.com 1
louis@media.berkeley.edu 3
cwen@iupui.edu 5
antranig@caret.cam.ac.uk 1
rjlowe@iupui.edu 2
gsilver@umich.edu 3
david.horwitz@uct.ac.za 4
wagnermr@iupui.edu 1
zqian@umich.edu 4
stephen.marquard@uct.ac.za 2
ray@media.berkeley.edu 1</pre>
</hint>
<exercise>
<statement>
<p>Add code to the program below to figure out who has the most messages in the file. After all the data has been read and the dictionary <c>message_count</c> has been created, look through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum loops) to find who has the most messages,
and print how many messages the person has. For example, <c>message_count['cwen@iupui.edu']</c> should be <c>5</c>.</p>
</statement>
<program interactive="activecode" language="python" xml:id="dict_writecode9q_editor">
<input>
with open("mbox-short.txt", "r") as filename:
message_count = {}
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(message_count['cwen@iupui.edu'], '5', "message_count['cwen@iupui.edu']")
self.assertEqual(len(message_count), 11, "len(message_count)")
myTests().main()
</input>
</program>
<solution>
Add code to the program below to figure out who has the most messages in the file. After all the data has been read and the dictionary message_count has been created, look through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum loops) to find who has the most messages,
and print how many messages the person has. For example, message_count['cwen@iupui.edu'] should be 5.
<program xml:id="dict_writecode9a_editor" language="python"><input>
# Open file in read mode
with open("mbox-short.txt", "r") as filename:
# Create message_count dictionary
message_count = {}
# Create variable for lines of the file
messages = filename.readlines()
# Iterate through each message (each line)
for message in messages:
# Make sure the message has at least 2 elements
if len(message.split()) > 2:
# Assign the key to the first (0th) element of the message
key = message.split()[0]
if key == "From" or key == "From:":
# Assign the value to the second element of the message
value = message.split()[1]
# Check if key is already in dictionary
if value not in message_count.keys():
# if not, set the value to 1
message_count[value] = 1
else:
# if so, increase count for that value by 1
message_count[value] += 1
# Create variable to count emails
max_emails = 0
# Iterate through keys in dictionary
for key in message_count.keys():
# Check if the value for that key is greater than or equal to max_emails
if int(message_count[key]) >= max_emails:
# If so, reassign max_emails to that key
max_emails = int(message_count[key])
# Print the maximum number of emails
print(max_emails)
</input></program>
</solution>
</exercise>
<exercise label="dict_writecode10">
<statement>
<p>Write a program to record in the dictionary <c>message_count</c> the total number of messages from each domain name (not the whole address, just the part after the @ and before the space). At the end of the program, print out the contents of your dictionary.
The domains should be the keys of the dictionary, and the counts of the domains should be the values of the dictionary. For example, <c>message_count['iupui.edu']</c> should be <c>8</c>.</p>
</statement>
<program xml:id="dict_writecode10_editor" interactive="activecode" language="python">
<input>
with open("mbox-short.txt", "r") as filename:
message_count = {}
====
from unittest.gui import TestCaseGui
class myTests(TestCaseGui):
def testOne(self):
self.assertEqual(message_count['iupui.edu'], '8', "message_count['iupui.edu']")
self.assertEqual(len(message_count), 6, "len(message_count)")
myTests().main()
</input>
</program>
</exercise>
</section>