-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-06-loops.qmd
More file actions
294 lines (203 loc) · 6.65 KB
/
Copy pathpython-06-loops.qmd
File metadata and controls
294 lines (203 loc) · 6.65 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
---
title: "Loops"
---
<!-- # For Loops -->
*For* loops are very common in Python and are similar to *for* in other languages, but one nice twist with Python is
that you can iterate over any collection, e.g., a list, a character string, etc.
```py
for number in [2, 3, 5]: # number is the loop variable; [...] is a collection
print(number) # Python uses indentation to show the body of the loop
```
This is equivalent to:
```py
print(2)
print(3)
print(5)
```
What will this do:
```py
for number in [2, 3, 5]:
print(number)
print(number)
```
* the loop variable could be called anything
* the body of a loop can contain many statements
* use range to iterate over a sequence of numbers
```py
for i in 'hello':
print(i)
```
```py
for i in range(0,3):
print(i)
```
Let's sum numbers 1 to 10:
```py
total = 0
for number in range(10):
total += (number + 1) # 1. what's the other way to sum numbers 1 to 10? how about range(1,11)?
# 2. can you rewrite this entire code as a one-liner?
print(total)
```
::: {.callout-caution collapse="true"}
## Exercise 6.1
Write a Python code to revert a string, e.g. 'computer' should become 'retupmoc'.
:::
<!-- **Solution 1:** -->
<!-- ```py -->
<!-- n = '' -->
<!-- for i in 'computer': -->
<!-- n = i + n -->
<!-- print(n) -->
<!-- ``` -->
<!-- **Solution 2:** -->
<!-- ```py -->
<!-- a = list('computer') -->
<!-- a.reverse() -->
<!-- ''.join(a) # convert the list to a string -->
<!-- help(''.join) # concatenate all strings in the iterable with the separator from the original string -->
<!-- ``` -->
<!-- **Solution 3:** -->
<!-- ```py -->
<!-- 'computer'[::-1] -->
<!-- ``` -->
::: {.callout-caution collapse="true"}
## Exercise 6.2
Print a difference between two lists, e.g. [1, 2, 3, 4, 6, 10] and [1, 2, 5, 10].
:::
::: {.callout-caution collapse="true"}
## Exercise 6.3
Write a script to get the frequency of the elements in the list `a = [77, 9, 23, 67, 73, 21, 23, 9]`. You can google
this problem :)
:::
<!-- **Solution 1:** -->
<!-- ```py -->
<!-- a = [77, 9, 23, 67, 73, 21, 23, 9] -->
<!-- a.count(77) # prints 1 -->
<!-- a.count(9) # prints 2 -->
<!-- for i in a: -->
<!-- a.count(i) # counts the frequency of 'i' in list 'a' -->
<!-- ``` -->
<!-- **Solution 2:** -->
<!-- ```py -->
<!-- a = [77, 9, 23, 67, 73, 21, 23, 9] -->
<!-- for i in set(a): -->
<!-- print(i, "is seen", a.count(i)) # no redundant output -->
<!-- ``` -->
<!-- **Solution 3:** -->
<!-- ```py -->
<!-- a = [77, 9, 23, 67, 73, 21, 23, 9] -->
<!-- import collections -->
<!-- print(collections.Counter(a)) -->
## While loops
Since we talk about loops, we should also briefly mention *while* loops, e.g.
```py
x = 2
while x > 1.:
x /= 1.1
print(x)
```
::: {.callout-caution collapse="true"}
## Exercise 6.4
Remove all occurrences of a specific item in a list, e.g. in this case number 20 in the list `[5, 20, 15, 20,
25, 50, 20]`, so it becomes `[5, 15, 25, 50]`.
**Hint**: use `while` to check if 20 is still in the list.
:::
<!-- ```py -->
<!-- a = [5, 20, 15, 20, 25, 50, 20] -->
<!-- while 20 in a: -->
<!-- a.remove(20) -->
<!-- ``` -->
## More on lists in loops
You can also form a *zip* object of tuples from two lists of the same length:
```py
for i, j in zip(a,b):
print(i,j)
```
And you can create an *enumerate* object from a list:
```py
for i, j in enumerate(b): # creates a list of tuples with an iterator as the first element
print(i,j)
```
<!-- **Exercise:** Write a script to sort a list in increasing order by the last element in each tuple, e.g., -->
<!-- input = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] should result in -->
<!-- [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]. -->
::: {.callout-caution collapse="true"}
## Exercise 6.5
Write a program to add two lists index-wise, e.g. `['M', 'na', 'i', 'Stu']` and `['y', 'me', 's', 'art']`
should produce a single list `['My', 'name', 'is', 'Stuart']`.
:::
<!-- ```py -->
<!-- a = ['M', 'na', 'i', 'Stu'] -->
<!-- b = ['y', 'me', 's', 'art'] -->
<!-- c = [] -->
<!-- for i, j, in zip(a,b): -->
<!-- c.append(i+j) -->
<!-- ``` -->
### List comprehensions
It's a compact way to create new lists based on existing lists/collections. Let's list squares of numbers
from 1 to 10:
```py
[x**2 for x in range(1,11)]
```
Of these, list only odd squares:
```py
[x**2 for x in range(1,11) if x%2==1]
```
The first list in the previous section was also generated via a list comprehension:
```py
events = [random.randint(0,2024) for i in range(10)]
```
You can also use list comprehensions to combine information from two or more lists:
```py
week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
weekend = ['Sat', 'Sun']
print([day for day in week]) # the entire week
print([day for day in week if day not in weekend]) # only the weekdays
print([day for day in week if day in weekend]) # in both lists
```
The syntax is:
```py
[something(i) for i in list1 if i [not] in list2 if i [not] in list3 ...]
```
::: {.callout-caution collapse="true"}
## Exercise 6.6
Remove empty strings from the list of strings, e.g. `["Mike", "", "Emma", "Kelly", "", "Brad"]` should become
`["Mike", "Emma", "Kelly", "Brad"]`.
:::
<!-- ```py -->
<!-- a = ["Mike", "", "Emma", "Kelly", "", "Brad"] -->
<!-- [i for i in a if len(i)>1] -->
<!-- ``` -->
::: {.callout-caution collapse="true"}
## Exercise 6.7
Write a one-line code to sum up the squares of numbers from 1 to 100.
:::
::: {.callout-caution collapse="true"}
## Exercise 6.8
Write a script to build a list of words that are shorter than `n` characters from a given list of words
`['red', 'green', 'white', 'black', 'pink', 'yellow']`.
:::
<!-- abc -->
<!-- Write a program to remove duplicates from a list. -->
<!-- abc -->
<!-- Write a program to check if a list is empty or not. -->
::: {.callout-caution collapse="true"}
## Exercise 6.9
Write a program to flatten a nested list, e.g. `[[11, 21.0, 3.5], ['Mercury', 'Venus', 'Earth'], 'hello']`
should become `[11, 21.0, 3.5, 'Mercury', 'Venus', 'Earth', 'hello']`.
**Hint**: try two nested loops, or maybe extend two nested loops to a nested list comprehension.
:::
<!-- ```py -->
<!-- a = [[11, 21.0, 3.5], ['Mercury', 'Venus', 'Earth'], 'hello'] -->
<!-- [j for i in a for j in i] -->
<!-- ``` -->
<!-- abc -->
<!-- Write a program to check whether two lists are circularly identical. -->
<!-- abc -->
<!-- Write a program to check whether a list contains a sublist. -->
::: {.callout-caution collapse="true"}
## Exercise 6.10
Write a program to convert a list of multiple integers into a single integer with all their digits combined,
e.g. a list `[11, 33, 50]` should become 113350.
:::