Every exercise in 20_collections.ipynb, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.
Exercise 3.1. The oldest heads of household
The task
Finish oldest(ages, n) so that it returns the n highest ages, from highest down, as a list. It must not change ages.
| call | returns |
|---|---|
oldest([47, 18, 63, 35, 52], 2) |
[63, 52] |
oldest([30, 30, 41], 3) |
[41, 30, 30] |
If the check is red: common causes
- The lowest ages: the list is sorted from lowest up. Add
reverse=True. None:.sort()sorts in place and gives back nothing. Usesorted(...), which gives back the new list.- One age too many or too few: a slice
[:n]stops before positionn, so it already holds exactlynvalues.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Sort a copy from highest to lowest, then slice off the first n: the slice is exactly the n highest, already in order.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def oldest(ages, n): return sorted(ages, reverse=True)[:n]Why each part is there
sorted(ages, reverse=True)gives a new list from highest to lowest and leavesagesalone.ages.sort(reverse=True)would reorder the list the caller gave, which a function asked for "the oldest" has no business doing.[:n]takes the firstnvalues of that sorted list. Whennis larger than the list, a slice simply stops at the end, so no error.- Ages that appear twice stay twice:
[41, 30, 30]has two heads aged 30, and both count.
Exercise 3.2. Add a household without changing the list
The task
The enumerators keep a sorted list of household IDs. Finish with_household(ids, new_id) so that it returns a new sorted list with new_id added, and leaves ids as it was. The cell after Try it says whether your function leaves the list it is given unchanged; the check after that, whether its results are right.
| call | returns |
|---|---|
with_household(["H001", "H004"], "H002") |
["H001", "H002", "H004"] |
If the check is red: common causes
- Green, but the cell above it is red: the result is right, but
idswas changed. Useids + [new_id]instead of.append. TypeError: can only concatenate list (not "str") to list: wrap the new ID in brackets,[new_id].- Not in order: return
sorted(...)of the new list.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
+ joins two lists into a new one, so ids + [new_id] holds every ID without touching ids; sorted(...) puts the new list in order.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def with_household(ids, new_id): return sorted(ids + [new_id])Why each part is there
[new_id]is a list of one value:+joins lists to lists, soids + new_id(a text) raises aTypeError.ids.append(new_id)would also add the ID, but to the caller's list: the enumerators' own list would change behind their back, which is exactly what the task rules out.sorted(...)gives back a new list, so the result is in order andidskeeps its own order.
Exercise 3.3. The crops a barangay grows
The task
Each farming household reports its main crop. Finish distinct_crops(reported) so that it returns the crops reported, each once, in alphabetical order, as a list.
| call | returns |
|---|---|
distinct_crops(["Palay", "Corn", "Palay", "Mango"]) |
["Corn", "Mango", "Palay"] |
If the check is red: common causes
{...}in curly brackets: that is the set itself. Returnsorted(...)of it, which is a list.- Repeats in the result: the list was sorted, but never made into a set.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A set keeps each value once; sorting it gives a list in a fixed, alphabetical order.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def distinct_crops(reported): return sorted(set(reported))Why each part is there
set(reported)drops the repeats. A set has no order of its own, so it cannot be the answer as it is.sorted(...)accepts any collection and always gives back a list, here in alphabetical order.- Capitals count in sorting and in sets:
"palay"and"Palay"are two crops to Python. Cleaning such text is module 6.
Exercise 3.4. One line about a household
The task
Finish summary(record) so that it returns a line such as H001: 5 members in Malanday, from a household's dictionary.
| call | returns |
|---|---|
summary({"id": "H001", "barangay": "Malanday", "members": 5, ...}) |
"H001: 5 members in Malanday" |
If the check is red: common causes
KeyError: a key is misspelt. The keys are"id","members"and"barangay", all lower case.NameError: name 'members' is not defined: the f-string uses{members}; inside the function the value isrecord["members"].
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A record's values are reached by their keys, so the line is an f-string with three lookups in it.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def summary(record): return f"{record['id']}: {record['members']} members in {record['barangay']}"Why each part is there
record["id"],record["members"]andrecord["barangay"]take each value by its key. The keys are text, so they need quotes inside the brackets.- Inside an f-string that is itself in double quotes, the keys use single quotes (
{record['id']}), or the inner quote would end the text early on Python before 3.12. - The other keys of the record (the head's age, the crop) are simply not used: a function reads only what it needs.
Exercise 3.5. A corrected record
The task
A revisit finds a household has a different number of members. Finish corrected(record, members) so that it returns a new dictionary, the same as record but with members changed, and leaves record as it was.
| call | returns |
|---|---|
corrected({"id": "H003", "members": 2, ...}, 3) |
{"id": "H003", "members": 3, ...} |
If the check is red: common causes
- Green, but the cell above it is red: the result is right, but the record given was changed. Build a new dictionary with
{**record, "members": members}. - The old number of members:
"members": membersis written before**record, so the old value overwrites it. Put it after.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
{**record, "members": members} copies every key and value of the record into a new dictionary, then sets members, so the original record is never touched.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def corrected(record, members): return {**record, "members": members}Why each part is there
**recordinside curly brackets unpacks the record: every key and its value go into the new dictionary."members": memberscomes after it, so it replaces the copied value. Written first, it would be overwritten by the old one.record["members"] = memberschanges the record the caller gave: the original survey record would be lost, which is what a correction must never do.