4 exercises that build on the Python Numbers lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.
What this lesson covers: Python has three built-in number types, int for whole numbers, float for decimal numbers and complex for numbers with an imaginary part, and each follows its own rules for size, division and precision. By the end you can tell int, float and complex apart, write readable number literals, use //, %, ** and divmod, round and format results, and avoid the 0.1 + 0.2 float trap. You will practise: Minutes to hours and minutes; Predict the division results; Fix the price check; Split a bill in whole cents.
0 / 4 completed
Python Numbers practice exercises
1. Minutes to hours and minutes
Write codeEasy✓ Completed
Write a function to_hours_minutes(total_minutes) that returns a tuple (hours, minutes). For example to_hours_minutes(135) returns (2, 15). Use // and % or divmod().
Hint: // rounds down towards minus infinity, / always gives a float, and round() sends halves to the nearest even number.
Actual output
3 1
-4 1
<class 'float'>
2 4
3. Fix the price check
Fix the bugMedium✓ Completed
total_matches(prices, expected) should be True when the prices add up to the expected total, but float errors make it fail for [0.1, 0.7] and 0.8. Fix the function with math.isclose().
Write split_bill(total_cents, people) that returns a list of people integers adding up to exactly total_cents. The shares may differ by at most one cent, with the larger shares first. Example: split_bill(1001, 3) returns [334, 334, 333]. Use divmod() and a loop, no floats.
Your code
def split_bill(total_cents, people):
shares = []
# base share and leftover cents: divmod(total_cents, people)
return shares
print(split_bill(1001, 3))
Hint: base, extra = divmod(total_cents, people). The first extra people pay base + 1 and everyone else pays base.
One possible solution
def split_bill(total_cents, people):
base, extra = divmod(total_cents, people)
shares = []
for i in range(people):
if i < extra:
shares.append(base + 1)
else:
shares.append(base)
return shares
print(split_bill(1001, 3))