-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-06-01.qmd
406 lines (323 loc) · 8.22 KB
/
slides-06-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
401
402
403
404
405
406
---
title: "lists (slides)"
format: revealjs
slide-number: true
df-print: kable
---
# CSc 110 - Lists
## Sequences
We've worked with `strings`, which are sequences in Python. Sequences can be indexed with `[ ]`:
```{python}
#| eval: true
#| echo: true
word = "uncopyrightable"
word[0] # returns first character in string
```
```{python}
#| eval: true
#| echo: true
word[1] # returns second character in string
```
We also have `lists` in Python, which are also sequences and can indexed with `[ ]`:
```{python}
#| eval: true
#| echo: true
numbers = [4, 2, 5, 7]
numbers[0] # returns first item in list
```
## Data Structures
- Data structures is a way to organize data when coding
- Data structures allow for easy access and **modification** of values
- You can see data structures as a collection of data values
- In Python `lists` are a data structure that is:
- mutable (you can change the values in it)
- unordered -- you can have repeated elements in a list
## Creating lists
```{python}
#| eval: true
#| echo: true
# empty list
no_numbers = []
# list of integers
numbers = [1, 5, 2, 10, 7]
# list of strings
names = ['ron', 'joe', 'kyle']
# mixed types list
values = [1, 1.15, 7, 1.75, 'those']
```
## Evaluate the expressions
```{python}
#| eval: false
#| echo: true
numbers = [2, 3, 2, 4, 5]
numbers[1] + numbers[4]
numbers = [2.0, 3, 1.3, 4]
numbers[0] * numbers[2]
words = ['the', 'bear', 'in', 'the', 'tree']
words[3] + words[4] + words[1]
floats = [1.2, 3.4, 0.3, 1.0, 3.2]
len(floats)
```
## Evaluate the expressions
```{python}
#| eval: true
#| echo: true
numbers = [2, 3, 2, 4, 5]
numbers[1] + numbers[4]
```
```{python}
#| eval: true
#| echo: true
numbers = [2.0, 3, 1.3, 4]
numbers[0] * numbers[2]
```
```{python}
#| eval: true
#| echo: true
words = ['the', 'bear', 'in', 'the', 'tree']
words[3] + words[4] + words[1]
```
```{python}
#| eval: true
#| echo: true
floats = [1.2, 3.4, 0.3, 1.0, 3.2]
len(floats)
```
## Write a function
Its name is `sum_all` that takes a list of `values` as an argument.
It runs a loop that iterates through the number in `values` summing all numbers.
It returns the sum of all numbers in `values`.
HINT: a) create a variable that accumulate the sum and b) use `while`.
Name your file `sum_list.py` and submit to Gradescope.
```{python}
#| eval: false
#| echo: true
assert sum_all([2, 2, 2]) == 6
assert sum_all([1, 2, 1, 1]) == 5
assert sum_all([]) == 0
```
## Write a function -- solution
Add test cases to the solution below:
```{python}
#| eval: true
#| echo: true
def sum_all(values):
total = 0
index = 0
while index < len(values):
total += values[index]
index += 1
return total
def main():
assert sum_all([2, 2, 2]) == 6
assert sum_all([1, 2, 1, 1]) == 5
assert sum_all([]) == 0
main()
```
## Loop Table
We start with `index = 0` and `total = 0`:
```{python}
#| eval: false
#| echo: true
sum_all([2, 1, 5, 2, 3])
```
```{r}
#| eval: true
#| echo: false
#| warning: false
#| message: false
library(knitr)
library(tidyverse)
data.frame(index = c(0:5),
condition = c("True", "True", "True", "True",
"True", "False"),
`item` = c("2", "1", "5", "2", "3", "-"),
total = c("0 + 2 = 2", "2 + 1 = 3", "3 + 5 = 8",
"8 + 2 = 10", "10 + 3 = 13", "13")
) %>%
kable(col.names = c("index", "index < len(values)", "values[index]", "total"))
```
## Loop Table
Start with `index = 0` and `total = 0`:
```{python}
#| eval: false
#| echo: true
sum_all([2, 1, 3, 4])
```
```{r}
#| eval: true
#| echo: false
#| warning: false
#| message: false
data.frame(index = c("|", "| ", "| ", "| ",
"| ", "| "),
condition = c(" ", " ", " ", " ",
" ", " "),
`item` = c(" ", " ", " ", " ", " ", " "),
total = c(" ", " ", " ",
" ", " ", " ")
) %>%
kable(col.names = c("index", "index < len(values)", "values[index]", "total"))
```
## Loop Table -- solution
```{python}
#| eval: false
#| echo: true
sum_all([2, 1, 3, 4])
```
```{r}
#| eval: true
#| echo: false
#| warning: false
#| message: false
data.frame(index = c(0:4),
condition = c("True", "True", "True", "True",
"False"),
`item` = c("2", "1", "3", "4", "-"),
total = c("2", "3", "6",
"10", "10")
) %>%
kable(col.names = c("index", "index < len(numbers)", "numbers[index]", "total"))
```
# Python Tutor
You can also visualize code in python on [Python Tutor](https://pythontutor.com/visualize.html#mode=edit)
## Using a control variable
Remember how to get the max of three numbers?
```{python}
#| eval: true
#| echo: true
def max3(x, y, z):
max = x # assume max is first number
if y > max:
max = y # assumption is incorrect, assume y is max
if z > max:
max = z # assumption is incorrect, z is max
return max
def main():
print( max3(1, 2, 2) ) # 2
main()
```
Adapt this function (`max_list`) to take a list of numbers (for example `[1, 2, 2, 1, 3, 1, 1]`) instead of three numbers (use `while`).
## Max of list -- solution
```{python}
#| eval: true
#| echo: true
def max_list(numbers):
'''
Given a list of number, this function returns the highest number.
Args:
List of numeric values
Returns:
Max (float or integer, whatever value type is the highest)
'''
max = numbers[0]
index = 1
while index < len(numbers):
if numbers[index] > max:
max = numbers[index]
index += 1
return max
def main():
print( max_list([1, 2, 2, 1, 3, 1, 1]) ) # 3
print( max_list([3, 2, 2, 1, 0, 1, 1]) ) # 3
main()
```
## Loop table
We start with `index = 1` and `max = 2`:
```{python}
#| eval: false
#| echo: true
max_list([2, 1, 3, 1])
```
```{r}
#| eval: true
#| echo: false
#| warning: false
#| message: false
data.frame(index = c("|", "| ", "| ", "| ",
"| ", "| "),
condition = c(" ", " ", " ", " ",
" ", " "),
`item` = c(" ", " ", " ", " ", " ", " "),
total = c(" ", " ", " ",
" ", " ", " ")
) %>%
kable(col.names = c("index", "index < len(numbers)", "numbers[index]", "max"))
```
## Loop table -- solution
We start with `index = 1` and `max = 2`:
```{python}
#| eval: false
#| echo: true
max_list([2, 1, 3, 1])
```
```{r}
#| eval: true
#| echo: false
#| warning: false
#| message: false
data.frame(index = c(1:4),
condition = c("True", "True", "True", "False"),
`item` = c("1", "3", "1", "-"),
max = c("2", "3", "3", "3")) %>%
kable(col.names = c("index", "index < len(numbers)", "numbers[index]", "max"))
```
## Max solution
- What about empty lists?
- How to get the min instead?
```{python}
#| eval: false
#| echo: true
assert max_list([]) == None
assert max_list([2, 1, 3, 1]) == 3
```
## Max solution - empty lists
```{python}
#| eval: true
#| echo: true
def max_list(numbers):
max = None
index = 0
while index < len(numbers):
if max == None or numbers[index] > max:
max = numbers[index]
index += 1
return max
def main():
print( max_list([2, 1, 3, 1]) ) # 3
print( max_list([]) ) # None
main()
```
## Write a function
Its name is `double` that takes a list of numeric variables as argument.
It iterates over the list (use `while`) doubling (multiplying by two) each value in the list.
It returns the modified list.
Name your file `double.py` and submit it to gradescope.
```{python}
#| eval: false
#| echo: true
assert double([0, 1, 2, 3]) == [0, 2, 4, 6]
```
## Write a function -- solution
```{python}
#| eval: false
#| echo: true
def double(numbers):
index = 0
while index < len(numbers):
numbers[index] *= 2
index += 1
return numbers
def main():
original_list = [0, 1, 2, 3]
new_list = double(original_list)
assert original_list == new_list
assert original_list == [0, 2, 4, 6]
print("Passed all tests")
main()
```
## Slicing lists
* Range -- `list[2:4]`
* Whole list -- `list[:]`
* Everything but last character -- `list[:-1]`
The same slicing can be done with strings