Skip to content

Commit bfa73c2

Browse files
authored
Merge branch 'UofT-DSI:main' into main
2 parents 2cdfe0a + c555065 commit bfa73c2

4 files changed

Lines changed: 2300 additions & 3 deletions

File tree

01_materials/slides/07_control_flow.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2465,7 +2465,7 @@
24652465
"id": "49190dce"
24662466
},
24672467
"source": [
2468-
"The `get()` method provides a safe way to work with dictionary values. It takes the name of the key to look up and the default value to create a new key:value pair if the key does not exist."
2468+
"The get() method provides a safe way to work with dictionary values. It takes the name of the key to look up and returns the corresponding value if the key exists; otherwise, it returns a specified default value without modifying the dictionary."
24692469
]
24702470
},
24712471
{
Lines changed: 333 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,333 @@
1-
{"cells":[{"cell_type":"markdown","metadata":{"id":"4e2hspYloycG"},"source":["# Control Flow\n","## Practice Problems"]},{"cell_type":"markdown","metadata":{"id":"W6-SVI7SqNWb"},"source":["### 1. Write a conditional that prints different messages if a bank account balance is below `$`3,000, between `$`3,000 and `$`10,000, or over `$`10,000.\n","\n","HINT: You can check if a value `x` is between two other values with a condition like `5 <= x <= 10`, but you can also solve this problem by strategically ordering conditions."]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":199,"status":"ok","timestamp":1668023835926,"user":{"displayName":"Kaylie Lau","userId":"01284785813595846851"},"user_tz":300},"id":"x92XbNTc9eYN","outputId":"5fd6a60f-13fa-45b9-f231-7aa111d1de7b"},"outputs":[],"source":["# Your code goes here"]},{"cell_type":"markdown","metadata":{},"source":["<details>\n"," <summary>Answer</summary>\n","\n"," ```python\n"," balance = 3000\n","\n"," if balance < 3000:\n"," print('Your balance is under $3,000')\n"," elif balance <= 10000:\n"," print('Your balance is between $3,000 and $10,000')\n"," else:\n"," print('Your balance is over $10,000.')\n","\n"," # This would also be a valid solution:\n"," \n"," if balance < 3000:\n"," print('Your balance is under $3,000')\n"," elif balance >= 3000 and balance <= 10000:\n"," print('Your balance is between $3,000 and $10,000')\n"," else:\n"," print('Your balance is over $10,000.')\n","\n"," # And so would this:\n","\n"," if balance < 3000:\n"," print('Your balance is under $3,000')\n"," elif 3000 <= balance <= 10000:\n"," print('Your balance is between $3,000 and $10,000')\n"," else:\n"," print('Your balance is over $10,000.')\n"," ```\n","</details>"]},{"cell_type":"markdown","metadata":{"id":"-eLr_oCiqRiH"},"source":["### 2. Create a list, `books`, containing the following items: `'War and Peace', 'Pride and Prejudice', 'Mockingjay', 'Three Musketeers', 'The Adventures of Robinson Crusoe', 'Yevgeniy Onegin'`. Then:\n","\n","- Using slicing or indexing, create the following:\n"," - An empty list\n"," - The last item of `books`\n"," - List of three items: 'Three Musketeers', 'The Adventures of Robinson Crusoe', 'Yevgeniy Onegin'.\n"," \n","- Using list methods:\n"," - Remove 'Pride and Prejudice' from the list.\n"," - Insert 'Harry Potter and the Chamber of Secrets' after 'Mockingjay'.\n","\n","HINT: Try using the same number as the starting index and ending index of a slice. Useful list methods include `remove()` and `insert()`."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"7DuSnDQ9-Cs0"},"outputs":[],"source":["# Your code goes here"]},{"cell_type":"markdown","metadata":{},"source":["<details>\n"," <summary>Answer</summary>\n","\n"," ```python\n"," books = ['War and Peace', 'Pride and Prejudice', 'Mockingjay', 'Three Musketeers', 'The Adventures of Robinson Crusoe', 'Yevgeniy Onegin']\n","\n"," # an empty list\n"," books[0:0]\n","\n"," # the last item\n"," books[-1]\n","\n"," # the last three items\n"," books[-3:]\n","\n"," # remove 'Pride and Prejudice'\n"," books.remove('Pride and Prejudice')\n","\n"," # Insert Harry Potter and the Chamber of Secrets after Mockingjay\n"," # If you did not remove Pride and Prejudice, the index would be 3, not 2\n"," books.insert(2, 'Harry Potter and the Chamber of Secrets')\n","\n"," books\n"," ```\n","</details>"]},{"cell_type":"markdown","metadata":{"id":"1P3cHY0MqWP_"},"source":["### 3. Given the list `people`, sort it by people's first name, last name and age. Store the sorted lists as `by_first_name`, `by_last_name`, and `by_age`, respectively. \n","`people = [('Mark', 'Harrison', 56), ('Ken', 'Wolseley', 23), ('Emily', 'Robinson', 77)]`\n","\n","HINT 1: We want our sorting function to return a new list, rather than modifying in place.\n","\n","HINT 2: `sorted()` accepts a `key` argument. This argument is the name of a function to use when sorting list elements."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ReUtuKtk_CH6"},"outputs":[],"source":["# Your code goes here"]},{"cell_type":"markdown","metadata":{},"source":["<details>\n"," <summary>Answer</summary>\n","\n"," ```python\n"," #Here, we have to write functions to get the first, second, and third items in a list.\n"," #Then, we can use those functions as the keys for sorted().\n","\n"," people = [('Mark', 'Harrison', 56), ('Ken', 'Wolseley', 23), ('Emily', 'Robinson', 77)]\n","\n"," def get_first_item(lst):\n"," return lst[0]\n","\n"," def get_second_item(lst):\n"," return lst[1]\n","\n"," def get_third_item(lst):\n"," return lst[2]\n","\n"," by_first_name = sorted(people, key=get_first_item)\n"," by_last_name = sorted(people, key=get_second_item)\n"," by_age = sorted(people, key=get_third_item)\n"," ```\n","</details>"]},{"cell_type":"markdown","metadata":{"id":"UpMWlbwrqZDz"},"source":["### 4. Write a function called `dict_intersect` that takes two dictionaries, `d1` and `d2`, as arguments and returns a set that contains only the keys found in both of the original dictionaries.\n","\n","HINT: Let's break this down into steps. We need to:\n","* Get the keys in `d1`\n","* Get the keys in `d2`\n","* Convert them both to sets\n","* Find their intersection\n","\n","HINT: Some useful functions and methods are `keys()`, `set()`, and `intersection()`."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"TdBwT7dYACOY"},"outputs":[],"source":["# Your code goes here"]},{"cell_type":"markdown","metadata":{},"source":["<details>\n"," <summary>Answer</summary>\n","\n"," ```python\n"," def dict_intersect(d1, d2):\n"," '''Return the set of keys found in both d1 and d2.\n"," >>> dict_intersect({'a': 'A', 'b': 'B', 'c': 'C'}, {'a': 'alpha', 'b': 'beta'})\n"," {'a', 'b'}\n"," >>> dict_intersect({'a': 1, 'b': 2}, {'c': 3, 'd': 2})\n"," set()\n"," '''\n"," d1_keys = set(d1.keys())\n"," d2_keys = set(d2.keys())\n"," return d1_keys.intersection(d2_keys)\n"," ```\n","</details>"]},{"cell_type":"markdown","metadata":{"id":"hW3Q-AHFqbZL"},"source":["### 5. Write a loop that iterates over the two lists below simultaneously. For each pair of values, print the first number divided by the second. When the program encounters a zero divisor, it should skip the pair without printing anything. \n","\n","HINT: We can exit a loop early with `break`.\n","\n","HINT 2: Remember that we can bundle two lists pairwise with `zip()`."]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":7,"status":"ok","timestamp":1668024643760,"user":{"displayName":"Kaylie Lau","userId":"01284785813595846851"},"user_tz":300},"id":"JgcenI9Mngvz","outputId":"630f1104-533a-4210-ebd1-575a9b69760e"},"outputs":[],"source":["# Your code goes here"]},{"cell_type":"markdown","metadata":{},"source":["<details>\n"," <summary>Answer</summary>\n","\n"," ```python\n"," dividends = [100, 37.5, -12]\n"," divisors = [8, 0, -3]\n","\n"," for x, y in zip(dividends, divisors):\n"," if y == 0:\n"," continue\n"," else:\n"," print(x/y)\n"," ```\n","</details>"]}],"metadata":{"colab":{"authorship_tag":"ABX9TyOqN1klgwmxsG8wtOHzdOL5","collapsed_sections":[],"provenance":[]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {
6+
"id": "4e2hspYloycG"
7+
},
8+
"source": [
9+
"# Control Flow\n",
10+
"## Practice Problems"
11+
]
12+
},
13+
{
14+
"cell_type": "markdown",
15+
"metadata": {
16+
"id": "W6-SVI7SqNWb"
17+
},
18+
"source": [
19+
"### 1. Write a conditional that prints different messages if a bank account balance is below `$`3,000, between `$`3,000 and `$`10,000, or over `$`10,000.\n",
20+
"\n",
21+
"HINT: You can check if a value `x` is between two other values with a condition like `5 <= x <= 10`, but you can also solve this problem by strategically ordering conditions."
22+
]
23+
},
24+
{
25+
"cell_type": "code",
26+
"execution_count": null,
27+
"metadata": {
28+
"colab": {
29+
"base_uri": "https://localhost:8080/"
30+
},
31+
"executionInfo": {
32+
"elapsed": 199,
33+
"status": "ok",
34+
"timestamp": 1668023835926,
35+
"user": {
36+
"displayName": "Kaylie Lau",
37+
"userId": "01284785813595846851"
38+
},
39+
"user_tz": 300
40+
},
41+
"id": "x92XbNTc9eYN",
42+
"outputId": "5fd6a60f-13fa-45b9-f231-7aa111d1de7b"
43+
},
44+
"outputs": [],
45+
"source": [
46+
"# Your code goes here"
47+
]
48+
},
49+
{
50+
"cell_type": "markdown",
51+
"metadata": {},
52+
"source": [
53+
"<details>\n",
54+
" <summary>Answer</summary>\n",
55+
"\n",
56+
" ```python\n",
57+
" balance = 3000\n",
58+
"\n",
59+
" if balance < 3000:\n",
60+
" print('Your balance is under $3,000')\n",
61+
" elif balance <= 10000:\n",
62+
" print('Your balance is between $3,000 and $10,000')\n",
63+
" else:\n",
64+
" print('Your balance is over $10,000.')\n",
65+
"\n",
66+
" # This would also be a valid solution:\n",
67+
" \n",
68+
" if balance < 3000:\n",
69+
" print('Your balance is under $3,000')\n",
70+
" elif balance >= 3000 and balance <= 10000:\n",
71+
" print('Your balance is between $3,000 and $10,000')\n",
72+
" else:\n",
73+
" print('Your balance is over $10,000.')\n",
74+
"\n",
75+
" # And so would this:\n",
76+
"\n",
77+
" if balance < 3000:\n",
78+
" print('Your balance is under $3,000')\n",
79+
" elif 3000 <= balance <= 10000:\n",
80+
" print('Your balance is between $3,000 and $10,000')\n",
81+
" else:\n",
82+
" print('Your balance is over $10,000.')\n",
83+
" ```\n",
84+
"</details>"
85+
]
86+
},
87+
{
88+
"cell_type": "markdown",
89+
"metadata": {
90+
"id": "-eLr_oCiqRiH"
91+
},
92+
"source": [
93+
"### 2. Create a list, `books`, containing the following items: `'War and Peace', 'Pride and Prejudice', 'Mockingjay', 'Three Musketeers', 'The Adventures of Robinson Crusoe', 'Yevgeniy Onegin'`. Then:\n",
94+
"\n",
95+
"- Using slicing or indexing, create the following:\n",
96+
" - An empty list\n",
97+
" - The last item of `books`\n",
98+
" - List of three items: 'Three Musketeers', 'The Adventures of Robinson Crusoe', 'Yevgeniy Onegin'.\n",
99+
" \n",
100+
"- Using list methods:\n",
101+
" - Remove 'Pride and Prejudice' from the list.\n",
102+
" - Insert 'Harry Potter and the Chamber of Secrets' after 'Mockingjay'.\n",
103+
"\n",
104+
"HINT: Try using the same number as the starting index and ending index of a slice. Useful list methods include `remove()` and `insert()`."
105+
]
106+
},
107+
{
108+
"cell_type": "code",
109+
"execution_count": null,
110+
"metadata": {
111+
"id": "7DuSnDQ9-Cs0"
112+
},
113+
"outputs": [],
114+
"source": [
115+
"# Your code goes here"
116+
]
117+
},
118+
{
119+
"cell_type": "markdown",
120+
"metadata": {},
121+
"source": [
122+
"<details>\n",
123+
" <summary>Answer</summary>\n",
124+
"\n",
125+
" ```python\n",
126+
" books = ['War and Peace', 'Pride and Prejudice', 'Mockingjay', 'Three Musketeers', 'The Adventures of Robinson Crusoe', 'Yevgeniy Onegin']\n",
127+
"\n",
128+
" # an empty list\n",
129+
" books[0:0]\n",
130+
"\n",
131+
" # the last item\n",
132+
" books[-1]\n",
133+
"\n",
134+
" # the last three items\n",
135+
" books[-3:]\n",
136+
"\n",
137+
" # remove 'Pride and Prejudice'\n",
138+
" books.remove('Pride and Prejudice')\n",
139+
"\n",
140+
" # Insert Harry Potter and the Chamber of Secrets after Mockingjay\n",
141+
" # If you did not remove Pride and Prejudice, the index would be 3, not 2\n",
142+
" books.insert(2, 'Harry Potter and the Chamber of Secrets')\n",
143+
"\n",
144+
" books\n",
145+
" ```\n",
146+
"</details>"
147+
]
148+
},
149+
{
150+
"cell_type": "markdown",
151+
"metadata": {
152+
"id": "1P3cHY0MqWP_"
153+
},
154+
"source": [
155+
"### 3. Given the list `people`, sort it by people's first name, last name and age. Store the sorted lists as `by_first_name`, `by_last_name`, and `by_age`, respectively. \n",
156+
"`people = [('Mark', 'Harrison', 56), ('Ken', 'Wolseley', 23), ('Emily', 'Robinson', 77)]`\n",
157+
"\n",
158+
"HINT 1: We want our sorting function to return a new list, rather than modifying in place.\n",
159+
"\n",
160+
"HINT 2: `sorted()` accepts a `key` argument. This argument is the name of a function to use when sorting list elements."
161+
]
162+
},
163+
{
164+
"cell_type": "code",
165+
"execution_count": null,
166+
"metadata": {
167+
"id": "ReUtuKtk_CH6"
168+
},
169+
"outputs": [],
170+
"source": [
171+
"# Your code goes here"
172+
]
173+
},
174+
{
175+
"cell_type": "markdown",
176+
"metadata": {},
177+
"source": [
178+
"<details>\n",
179+
" <summary>Answer</summary>\n",
180+
"\n",
181+
" ```python\n",
182+
" #Here, we have to write functions to get the first, second, and third items in a list.\n",
183+
" #Then, we can use those functions as the keys for sorted().\n",
184+
"\n",
185+
" people = [('Mark', 'Harrison', 56), ('Ken', 'Wolseley', 23), ('Emily', 'Robinson', 77)]\n",
186+
"\n",
187+
" def get_first_item(lst):\n",
188+
" return lst[0]\n",
189+
"\n",
190+
" def get_second_item(lst):\n",
191+
" return lst[1]\n",
192+
"\n",
193+
" def get_third_item(lst):\n",
194+
" return lst[2]\n",
195+
"\n",
196+
" by_first_name = sorted(people, key=get_first_item)\n",
197+
" by_last_name = sorted(people, key=get_second_item)\n",
198+
" by_age = sorted(people, key=get_third_item)\n",
199+
" ```\n",
200+
"</details>"
201+
]
202+
},
203+
{
204+
"cell_type": "markdown",
205+
"metadata": {
206+
"id": "UpMWlbwrqZDz"
207+
},
208+
"source": [
209+
"### 4. Write a function called `dict_intersect` that takes two dictionaries, `d1` and `d2`, as arguments and returns a set that contains only the keys found in both of the original dictionaries.\n",
210+
"\n",
211+
"HINT: Let's break this down into steps. We need to:\n",
212+
"* Get the keys in `d1`\n",
213+
"* Get the keys in `d2`\n",
214+
"* Convert them both to sets\n",
215+
"* Find their intersection\n",
216+
"\n",
217+
"HINT: Some useful functions and methods are `keys()`, `set()`, and `intersection()`."
218+
]
219+
},
220+
{
221+
"cell_type": "code",
222+
"execution_count": null,
223+
"metadata": {
224+
"id": "TdBwT7dYACOY"
225+
},
226+
"outputs": [],
227+
"source": [
228+
"# Your code goes here"
229+
]
230+
},
231+
{
232+
"cell_type": "markdown",
233+
"metadata": {},
234+
"source": [
235+
"<details>\n",
236+
" <summary>Answer</summary>\n",
237+
"\n",
238+
" ```python\n",
239+
" def dict_intersect(d1, d2):\n",
240+
" '''Return the set of keys found in both d1 and d2.\n",
241+
" >>> dict_intersect({'a': 'A', 'b': 'B', 'c': 'C'}, {'a': 'alpha', 'b': 'beta'})\n",
242+
" {'a', 'b'}\n",
243+
" >>> dict_intersect({'a': 1, 'b': 2}, {'c': 3, 'd': 2})\n",
244+
" set()\n",
245+
" '''\n",
246+
" d1_keys = set(d1.keys())\n",
247+
" d2_keys = set(d2.keys())\n",
248+
" return d1_keys.intersection(d2_keys)\n",
249+
" ```\n",
250+
"</details>"
251+
]
252+
},
253+
{
254+
"cell_type": "markdown",
255+
"metadata": {
256+
"id": "hW3Q-AHFqbZL"
257+
},
258+
"source": [
259+
"### 5. Write a loop that iterates over the two lists below simultaneously. For each pair of values, print the first number divided by the second. When the program encounters a zero divisor, it should skip the pair without printing anything. \n",
260+
"\n",
261+
"```python\n",
262+
"dividends = [100, 37.5, -12]\n",
263+
"divisors = [8, 0, -3]\n",
264+
"```\n",
265+
"\n",
266+
"HINT: We can exit a loop early with `break`.\n",
267+
"\n",
268+
"HINT 2: Remember that we can bundle two lists pairwise with `zip()`."
269+
]
270+
},
271+
{
272+
"cell_type": "code",
273+
"execution_count": null,
274+
"metadata": {
275+
"colab": {
276+
"base_uri": "https://localhost:8080/"
277+
},
278+
"executionInfo": {
279+
"elapsed": 7,
280+
"status": "ok",
281+
"timestamp": 1668024643760,
282+
"user": {
283+
"displayName": "Kaylie Lau",
284+
"userId": "01284785813595846851"
285+
},
286+
"user_tz": 300
287+
},
288+
"id": "JgcenI9Mngvz",
289+
"outputId": "630f1104-533a-4210-ebd1-575a9b69760e"
290+
},
291+
"outputs": [],
292+
"source": [
293+
"# Your code goes here"
294+
]
295+
},
296+
{
297+
"cell_type": "markdown",
298+
"metadata": {},
299+
"source": [
300+
"<details>\n",
301+
" <summary>Answer</summary>\n",
302+
"\n",
303+
" ```python\n",
304+
" dividends = [100, 37.5, -12]\n",
305+
" divisors = [8, 0, -3]\n",
306+
"\n",
307+
" for x, y in zip(dividends, divisors):\n",
308+
" if y == 0:\n",
309+
" continue\n",
310+
" else:\n",
311+
" print(x/y)\n",
312+
" ```\n",
313+
"</details>"
314+
]
315+
}
316+
],
317+
"metadata": {
318+
"colab": {
319+
"authorship_tag": "ABX9TyOqN1klgwmxsG8wtOHzdOL5",
320+
"collapsed_sections": [],
321+
"provenance": []
322+
},
323+
"kernelspec": {
324+
"display_name": "Python 3",
325+
"name": "python3"
326+
},
327+
"language_info": {
328+
"name": "python"
329+
}
330+
},
331+
"nbformat": 4,
332+
"nbformat_minor": 0
333+
}

0 commit comments

Comments
 (0)