-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-07-01.qmd
401 lines (300 loc) · 9.54 KB
/
slides-07-01.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
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
---
title: "mutability (slides)"
format: revealjs
slide-number: true
df-print: kable
---
# CSc 110 - Mutability
## Lists vs strings
- Lists are **mutable**
- Strings are **not**
- In addition to retrieving an item from a `list`, we can remove or change it (which is **not** something you can do with strings)
```{python}
#| echo: true
#| eval: true
songs = ["Lavender Haze", "Calm Down", "As It Was", "About Damn Time"]
songs
```
```{python}
#| echo: true
#| eval: true
songs[0] = "Flowers"
songs
```
## Lists are mutable
(strings are not)
Because lists are mutable:
- once a list is changed **inside** a function, that **change persists** when the function has finished running
- if your function changes a list, you don't strictly need to return that list -- we will be returning because that's what you need to be doing in the future
## Write a function
1. Its name is `make_all_even`
2. It takes one argument, a list of `integers`
3. It iterates over the list, changing odd numbers to even number (even up)
```{python}
#| eval: false
#| echo: true
test_integers = [1, 2, 3, 4]
assert make_all_even(test_integers) == test_integers
assert test_integers == [2, 2, 4, 4]
```
## Write a function -- solution 1
```{python}
#| eval: true
#| echo: true
def make_all_even(integers):
index = 0
while index < len(integers):
if integers[index] % 2 == 1:
integers[index] += 1
index += 1
return integers
def main():
test_integers = [1, 2, 3, 4]
make_all_even(test_integers)
assert test_integers == [2, 2, 4, 4]
main()
```
Let's visualize this on [Python Tutor](https://pythontutor.com/visualize.html#mode=edit)
## Write a function -- solution 2
```{python}
#| eval: true
#| echo: true
def make_all_even(integers):
index = 0
while index < len(integers):
integers[index] += integers[index] % 2
index += 1
return integers
def main():
test_integers = [1, 2, 3, 4]
make_all_even(test_integers)
assert test_integers == [2, 2, 4, 4]
main()
```
## Object References
- A variable doesn't store values, it stores a reference to an object that lives in your computer memory (RAM)
- The same variable name can be pointed to a different object
```{python}
#| eval: true
#| echo: true
title = "Dr."
title = "Ms."
```
- A variable name can point to an object that is already referenced by another variable
```{python}
#| eval: true
#| echo: true
last_name = "Brown"
name = last_name
```
## Examples
Strings are **not** mutable
```{python}
#| eval: true
#| echo: true
title = "Dr."
last_name = "Brown"
print(title + " " + last_name)
title = "Ms."
print(title + " " + last_name)
name = last_name # both point to the same object
last_name = "Silva" # a new object created, last_name point to the new object
print(title + " " + name) # name still point to the original string
```
Visualize these examples in [Python Tutor](https://pythontutor.com/visualize.html#mode=display)
## Examples
Lists are **mutable**
```{python}
#| eval: true
#| echo: true
names = ["Dr.", "Brown"]
print(names[0] + " " + names[1])
names[0] = "Ms."
print(names[0] + " " + names[1])
names_copy = names # both point to the same object
names[1] = "Silva" # the object been mutated, no new object created
print(names_copy[0] + " " + names_copy[1]) # both name and name_copy point to the mutated object
```
Visualize these examples in [Python Tutor](https://pythontutor.com/visualize.html#mode=display)
## Another example
```{python}
#| eval: true
#| echo: true
numbers = [50, 30, 80]
same_numbers = numbers
same_numbers[1] = 3000
numbers = "look, numbers"
same_numbers = numbers
same_numbers += "!"
```
Visualize these examples in [Python Tutor](https://pythontutor.com/visualize.html#mode=display)
## Object references
- A variable does not actually hold the value of the object within it
- Instead, it's a **reference** to the object
- The object is "sitting" somewhere in your computer's memory (RAM)
## Object references
- If you assign a value to an existing object, the variable references that object
```{python}
#| eval: true
#| echo: true
last_name = "Brown"
name = last_name
```
- If you assign it to a new object, the object is created, placed in memory, and then the variable references it
```{python}
#| eval: true
#| echo: true
title = "Dr."
title = "Ms." # "Dr." object will be removed from memory
```
- When there's no variable pointing to an object anymore, that object is removed from memory by Python's Garbage Collector (so you don't have to worry about memory leaks)
## Summary
When working with lists, once they are changed in a function, the changes happen to the object in memory
Changes to lists persist once the function has finished running
## `.pop()` list method
We will be using a few built-in list `methods`
Here's how `.pop()` works:
```{python}
#| echo: true
#| eval: true
songs = ["Lavender Haze", "Calm Down", "As It Was", "Her"]
songs
```
```{python}
#| echo: true
#| eval: true
songs.pop(0) # 'Her' index moves from 3 to 2
songs
```
```{python}
#| echo: true
#| eval: true
songs.pop(0) # 'Her' index moves from 2 to 1
songs
```
## Write two functions
1. Names are `remove_vowels_list` and `remove_vowels_string`
2. The first function takes a list of `characters` as argument, the second takes a single `string`
3. The first function removes (use `.pop(index)`) all vowels from the `characters` list, the second creates a `new_string` with only characters that are not vowels
4. The first function returns the original argument list, the second function returns the `new_string`
```{python}
#| eval: false
#| echo: true
assert remove_vowels_list(["b", "a", "n", "a", "n", "a"]) == ["b", "n", "n"]
assert remove_vowels_string("banana") == "bnn"
```
## Write two functions -- solution
```{python}
#| echo: true
#| eval: true
def remove_vowels_list(characters):
index = 0
while index < len(characters):
if characters[index] in "aeiou":
characters.pop(index)
else:
index += 1 # go to next index only if no item has been removed
return characters
def remove_vowels_string(string):
new_string = ""
index = 0
while index < len(string):
if string[index] not in "aeiou":
new_string += string[index]
index += 1
return new_string
def main():
test_characters = ["b", "a", "n", "a", "n", "a"]
test_string = "banana"
assert remove_vowels_list(test_characters) == test_characters
assert test_characters == ["b", "n", "n"]
assert remove_vowels_string("banana") == "bnn"
print(test_characters)
print(test_string)
main()
```
## List methods
We will be using the following list methods in this class:
- `.append()` adds an element at the end of the list: `list.append(value)`
- `.insert()` adds an element at the provided index: `list.insert(index, value)`
- `.pop()` removes a specific element at the provided index: `list.pop(index)`
- `.remove()` removes the first element with the provided value: `list.remove(value)`
## `.append()` list method
```{python}
#| echo: true
#| eval: true
songs = ["Lavender Haze", "Calm Down", "As It Was", "Her"]
songs
```
```{python}
#| echo: true
#| eval: true
songs.append("Attention")
songs
```
## Write a function
1. Its name is `indices_of_vowels`
2. It takes a single `string` as its parameter.
3. It returns a list of integers that represent the indices of the vowels in the original list
Test cases:
```{python}
#| echo: true
#| eval: false
assert indices_of_vowels("hello") == [1, 4]
assert indices_of_vowels("") == []
assert indices_of_vowels("aeiou") == [0, 1, 2, 3, 4]
```
## Write a function -- solution
```{python}
#| echo: true
#| eval: true
def indices_of_vowels(string):
result = [] # initialize empty list to hold indices
index = 0 # initialize index
while index < len(string):
if string[index] in "aeiou": # check if character is vowel
result.append(index) # append index to result
index += 1 # increment index
return result
def main():
assert indices_of_vowels("hello") == [1, 4]
assert indices_of_vowels("") == []
assert indices_of_vowels("aeiou") == [0, 1, 2, 3, 4]
print("Passed all tests.")
main()
```
## Quiz 06
<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 `reverse_list`
2. It takes a list as argument
3. It returns a new list with the items of the original list inverted
Test case:
```{python}
#| eval: false
#| echo: true
test_strings = ["banana", "apple", "grape"]
assert reverse_list(test_strings) == ["grape", "apple", "banana"]
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def reverse_list(items):
index = len(items) - 1 # initialize index
inverted_list = []
while index >= 0:
inverted_list.append(items[index])
index -= 1
return inverted_list
def main():
test_strings = ["banana", "apple", "grape"]
assert reverse_list(test_strings) == ["grape", "apple", "banana"]
print("Passed test")
main()
```