Every exercise in 40_functions.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 5.1. Yield per hectare
The task
Finish yield_per_hectare(harvest_kg, area_sqm) so that it returns a farm's yield in tonnes per hectare, rounded to two decimal places. A hectare is 10,000 square metres and a tonne is 1,000 kg.
| call | returns |
|---|---|
yield_per_hectare(2500, 5000) |
5.0 |
yield_per_hectare(4300, 12000) |
3.58 |
If the check is red: common causes
- Ten times too big or too small: one of the conversions is off. 1 hectare is 10,000 square metres; 1 tonne is 1,000 kg.
- Many decimal places: round the result to 2.
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
Convert both quantities to the units of the answer first, then divide: tonnes per hectare is tonnes divided by hectares.
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 yield_per_hectare(harvest_kg, area_sqm): tonnes = harvest_kg / 1000 hectares = area_sqm / 10000 return round(tonnes / hectares, 2)Why each part is there
harvest_kg / 1000is the harvest in tonnes andarea_sqm / 10000the area in hectares; naming them says what each number is.- Dividing tonnes by hectares gives tonnes per hectare. Dividing first and converting after is easy to get wrong by a factor of ten.
round(..., 2)comes last, so no rounding happens before the division.
Exercise 5.2. A share, with a default
The task
Finish share(part, whole, decimals=1) so that it returns part as a percentage of whole, rounded to decimals places: one decimal place when the caller does not say.
| call | returns |
|---|---|
share(1, 3) |
33.3 |
share(1, 3, decimals=3) |
33.333 |
share(1, 3, 0) |
33.0 |
If the check is red: common causes
- Right with two inputs, wrong with three: the body rounds to a fixed
1. Round todecimals. TypeError: share() missing 1 required positional argument: thedefline has no default; writedecimals=1.
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
The default lives in the parameter list, so the body just uses decimals: it is 1 when the caller leaves it out, and whatever the caller gives otherwise.
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 share(part, whole, decimals=1): return round(part / whole * 100, decimals)Why each part is there
decimals=1in thedefline is what makes the third input optional. The body never needs to check whether it was given.round(value, decimals)withdecimals0 still gives afloat(33.0), because the value rounded is a float.- Writing
round(..., 1)in the body would ignore what the caller asked for:share(1, 3, decimals=3)would still give33.3.
Exercise 5.3. Households by size, largest first
The task
Finish largest_first(records) so that it returns the households' IDs from the most members to the fewest. Households with the same number of members keep their order in the records.
| call | returns |
|---|---|
largest_first(households) |
["H002", "H008", "H001", "H006", "H003"] |
If the check is red: common causes
- Smallest first: add
reverse=True. TypeError: '<' not supported between instances of 'dict' and 'dict': the sort has nokey, so it tries to compare whole records.
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 the records by their members with a key, largest first, then take the ID of each sorted record.
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 largest_first(records): return [r["id"] for r in sorted(records, key=lambda r: r["members"], reverse=True)]Why each part is there
key=lambda r: r["members"]tellssortedwhat to compare: two whole dictionaries cannot be compared, their members can.reverse=Trueputs the largest first. Python's sort is stable, so households with the same members stay in their original order, even reversed.- The comprehension keeps only the IDs, in the sorted order;
recordsitself is not changed, becausesortedmakes a new list.
Exercise 5.4. Yields of the farms
The task
Finish farm_yields(records) so that it returns, for every household that farms, its yield per hectare (Exercise 5.1's function, which you can call), in the order of the records.
| call | returns |
|---|---|
farm_yields(households) |
[5.0, 3.58, 5.5, 7.75] |
If the check is red: common causes
ZeroDivisionError: a household that does not farm (area 0) is included. Keep onlyr["farms"].NotImplementedErroror a wrong yield: this function uses Exercise 5.1's; finish that one first.
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
Filter, then map: keep the farming households, and turn each into its yield with the function written in Exercise 5.1, so the formula lives in one place.
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 farm_yields(records): return [yield_per_hectare(r["harvest_kg"], r["area_sqm"]) for r in records if r["farms"]]Why each part is there
if r["farms"]leaves out households with no farm, whose area of 0 would makeyield_per_hectaredivide by zero.- Calling
yield_per_hectareinstead of writing the formula again means a fix to the formula is made once, and every use of it gets the fix. - The same can be written
list(map(lambda r: yield_per_hectare(...), filter(lambda r: r["farms"], records))); the comprehension says it in fewer brackets.
Exercise 5.5. A label for a household
The task
The class below describes a household. Its method label is for you to finish: it returns a line for a report with the ID, the members, and whether the household is large, using the class's own is_large. After you write it, run the class's cell again.
| call | returns |
|---|---|
Household("H002", 7, 63).label() |
"H002: 7 members, large" |
Household("H003", 2, 29).label() |
"H003: 2 members, not large" |
If the check is red: common causes
NameError: name 'members' is not defined: inside a method, the object's values areself.membersand so on.- Still not written after you edited it: run the cell with the class again, then this one.
TypeError: label() takes 0 positional arguments: the method's first parameter must beself.
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 method reaches the object's own data through self, and can call the object's other methods the same way, so the line reuses is_large rather than repeating its rule.
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 label(self): """A line about the household, for a report: 'H002: 7 members, large'.""" return f"{self.household_id}: {self.members} members, {'large' if self.is_large() else 'not large'}"Why each part is there
self.household_idandself.membersare the values__init__stored when the object was made.self.is_large()asks the object itself, so the rule for "large" stays in one method; if the barangay changes the rule, the label follows.- The conditional expression
"large" if ... else "not large"picks one of two texts inside the f-string.