-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-08-02.qmd
344 lines (263 loc) · 7.19 KB
/
slides-08-02.qmd
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
---
title: "for loops -- iterating over items (slides)"
format: revealjs
slide-number: true
df-print: kable
---
# CSc 110 - the other type of `for` loop
## Announcements
* Midterm 2 will be on next Wednesday, Oct 23.
* Review session next Tuesday, Oct 22 5-7pm
* Location: Gittings 129b
* Study guide: [xinchenyu.github.io/csc110-fall2024/pdfs/study-guide-2.pdf](https://xinchenyu.github.io/csc110-fall2024/pdfs/study-guide-2.pdf)
## Review of `for in range():`
```{python}
#| echo: true
#| eval: true
for n in range(5):
print(n)
```
```{python}
#| echo: true
#| eval: true
numbers = [2, 1, 4, 6, 23, 2]
for i in range(len(numbers)):
print(numbers[i])
```
## Introducing `for x in string:`
```{python}
#| echo: true
#| eval: true
string = "hello"
for n in string:
print(n)
```
## Introducing `for x in list:`
```{python}
#| echo: true
#| eval: true
numbers = [2, 1, 4, 6, 23, 2]
for n in numbers:
print(n)
```
## Write a function
Modify your `count_vowels` and `count_chars` functions.
Use `for x in string` instead of `for x in range(len(string))`.
```{python}
#| eval: false
#| echo: true
assert count_vowels("") == {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
assert count_vowels("banana") == {"a": 3, "e": 0, "i": 0, "o": 0, "u": 0}
assert count_chars("") == {}
assert count_chars("banana") == {"b": 1, "a": 3, "n": 2}
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def count_vowels(string):
counts = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
for char in string:
if char in counts:
counts[char] += 1
return counts
def main():
assert count_vowels("") == {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
assert count_vowels("banana") == {"a": 3, "e": 0, "i": 0, "o": 0, "u": 0}
print("Passed all tests.")
main()
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def count_chars(string):
counts = {}
for char in string:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
def main():
assert count_chars("") == {}
assert count_chars("banana") == {"b": 1, "a": 3, "n": 2}
print("Passed all tests.")
main()
```
## Quiz 07
<center>
<div class="cleanslate w24tz-current-time w24tz-large" style="display: inline-block !important; visibility: hidden !important; min-width:300px !important; min-height:145px !important;"><a href="//24timezones.com/Tucson/time" style="text-decoration: none" class="clock24" id="tz24-1695057604-c1393-eyJob3VydHlwZSI6IjEyIiwic2hvd2RhdGUiOiIwIiwic2hvd3NlY29uZHMiOiIwIiwiY29udGFpbmVyX2lkIjoiY2xvY2tfYmxvY2tfY2I2NTA4ODZjNDg0OWVlIiwidHlwZSI6ImRiIiwibGFuZyI6ImVuIn0=" title="World Time :: Tucson" target="_blank" rel="nofollow"></a>current time<div id="clock_block_cb650886c4849ee"></div></div>
<script type="text/javascript" src="//w.24timezones.com/l.js" async></script>
</center>
You have 10 minutes to complete the quiz.
No need to write `main()` function.
## Write a function
1. Its name is `max_list` that takes a list of numbers as argument.
2. It mutates the list, multiply each number by 2
3. It returns the highest value in the mutated numbers
Test cases:
```{python}
#| eval: false
#| echo: true
assert max_list([]) == None
assert max_list([2, 2, 1]) == 4
assert max_list([1, -3]) == 2
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def max_list(numbers):
max = None
for i in range(len(numbers)):
numbers[i] *= 2
for i in range(len(numbers)):
if max == None or numbers[i] > max:
max = numbers[i]
return max
def main():
assert max_list([]) == None
assert max_list([2, 2, 1]) == 4
assert max_list([1, -3]) == 2
print("pass")
main()
```
## Write a function
1. Its name is `tally_negatives`
1. It takes a list of `numbers` as argument
1. It returns a dictionary that maps each negative value in `numbers` to its frequency in `numbers`
Name your file as `tally_negatives.py` and submit to gradescope. Test cases:
```{python}
#| eval: false
#| echo: true
assert tally_negatives([1, -2, 0, -4, -2]) == {-2: 2, -4: 1}
assert tally_negatives([]) == {}
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def tally_negatives(numbers):
tally = {}
for n in numbers:
if n < 0:
if n not in tally:
tally[n] = 0
tally[n] += 1
return tally
def main():
assert tally_negatives([1, -2, 0, -4, -2]) == {-2: 2, -4: 1}
assert tally_negatives([]) == {}
print("Passed all tests.")
main()
```
## What happens when we do `for k in dictionary:`
```{python}
#| eval: true
#| echo: true
scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
for key in scores:
print(key)
```
## Methods for dictionaries
We can use `.values()` to get only the values in a dictionary:
```{python}
#| eval: true
#| echo: true
scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
scores.values()
```
We can use `.keys()` to get only the keys in a dictionary:
```{python}
#| eval: true
#| echo: true
scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
scores.keys()
```
We can use `.items()` to get tuples for keys and values:
```{python}
#| eval: true
#| echo: true
scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
scores.items()
```
## `for x in list`
```{python}
#| eval: true
#| echo: true
scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
for value in scores.values():
print(value)
```
```{python}
#| eval: true
#| echo: true
scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
for key in scores.keys():
print(key)
```
## `for key, value in dictionary.items()`
```{python}
#| eval: true
#| echo: true
scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}
for key, value in scores.items():
print(key, value)
```
## Write a function
1. Its name is `keys_and_values`
1. It takes a `dictionary` as argument
1. It returns a list with all the keys and values in the `dictionary`
Test cases:
```{python}
#| eval: false
#| echo: true
assert keys_and_values({'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}) == \
['A', 10, 'B', 25, 'C', 27, 'D', 10, 'E', 5]
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def keys_and_values(dictionary):
new_list = []
for key, value in dictionary.items():
new_list.append(key)
new_list.append(value)
return new_list
def main():
assert keys_and_values({'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}) == ['A', 10, 'B', 25, 'C', 27, 'D', 10, 'E', 5]
main()
```
## Write a function
1. Its name is `merge_dictionaries`
1. It takes two arguments: `dict_1` and `dict_2`
1. It mutates `dict_1`, by adding to it all key-values pairs in `dict_2`
1. If a key is in both dictionaries, the values are added
1. Don't use `.update()`
Test cases:
```{python}
#| echo: true
#| eval: false
dict_1 = {"a": 20, "e": 5}
dict_2 = {"e": 10, "i": 2}
assert merge_dictionaries(dict_1, dict_2) == {"a": 20, "e": 15, "i": 2}
```
## Write a function -- solution
```{python}
#| echo: true
#| eval: true
def merge_dictionaries(dict_1, dict_2):
for key, value in dict_2.items():
if key in dict_1:
dict_1[key] += value
else:
dict_1[key] = value
return dict_1
def main():
dict_1 = {"a": 20, "e": 5}
dict_2 = {"e": 10, "i": 2}
assert merge_dictionaries(dict_1, dict_2) == {"a": 20, "e": 15, "i": 2}
main()
```