Numeric Types · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: Convert to any base ✓ Passed
Write to_base(n, base) that returns the representation of the integer n in base (2 to 36) as a string, using the digits 0-9 and then A-Z.
- Negative numbers get a leading '-'; 0 is '0'. - Raise ValueError if base is outside 2–36. - The result must round-trip: int(to_base(n, b), b) == n.
def to_base(n, base):
# your code here
pass
def test_binary():
"""10 in base 2 is '1010'"""
assert to_base(10, 2) == '1010', f"got {to_base(10, 2)!r}"
def test_hex():
"""255 in base 16 is 'FF'"""
assert to_base(255, 16) == 'FF', f"got {to_base(255, 16)!r}"
def test_zero():
"""0 is '0' in any base"""
assert to_base(0, 7) == '0', f"got {to_base(0, 7)!r}"
def test_negative():
"""negative numbers get a leading minus"""
assert to_base(-10, 2) == '-1010', f"got {to_base(-10, 2)!r}"
def test_round_trip():
"""int(to_base(n, b), b) == n for many values and bases"""
for b in (2, 3, 7, 11, 16, 36):
for n in (1, 35, 36, 1000, 123456789, -4095):
s = to_base(n, b)
assert int(s, b) == n, f"to_base({n}, {b}) = {s!r} doesn't round-trip"
def test_bad_base():
"""bases outside 2-36 raise ValueError"""
for b in (1, 37):
try:
to_base(10, b)
except ValueError:
pass
else:
raise AssertionError(f"base {b} should raise ValueError")
Hints (3)
divmod(n, base)gives the remaining number and the last digit in one step.- Digits come out last-first, so reverse them (or insert each at the front).
- Handle the sign separately; work with
abs(n).
Show a solution
def to_base(n, base):
digit_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if not 2 <= base <= 36:
raise ValueError('base must be between 2 and 36')
if n == 0:
return '0'
sign = '-' if n < 0 else ''
n = abs(n)
digits = []
while n > 0:
n, m = divmod(n, base)
digits.append(digit_map[m])
return sign + ''.join(reversed(digits))Exercise 2: School rounding ✓ Passed
Python's round() sends exact ties to the even neighbor. Write round_half_away(x) that rounds a float to the nearest integer (returning an int), with ties rounded away from zero: 2.5 → 3, -2.5 → -3.
Be careful with 0.49999999999999994 (the largest float below 0.5). It must round to 0.
def round_half_away(x):
return round(x)
def test_ties():
"""ties go away from zero"""
for x, expected in [(0.5, 1), (1.5, 2), (2.5, 3), (-0.5, -1), (-2.5, -3)]:
got = round_half_away(x)
assert got == expected, f"round_half_away({x}) = {got}, expected {expected}"
def test_non_ties():
"""non-ties go to the nearest integer"""
for x, expected in [(2.4, 2), (2.6, 3), (-2.4, -2), (-2.6, -3), (7.0, 7), (0.0, 0)]:
got = round_half_away(x)
assert got == expected, f"round_half_away({x}) = {got}, expected {expected}"
def test_tricky_float():
"""0.49999999999999994 rounds to 0, not 1"""
got = round_half_away(0.49999999999999994)
assert got == 0, f"got {got}: adding 0.5 rounds the sum up to 1.0"
def test_returns_int():
"""the result is an int"""
assert type(round_half_away(2.5)) is int
Hints (2)
- Work with
abs(x)and put the sign back at the end. x + 0.5can itself be rounded by floating point. Compare the fractional parta - math.floor(a)with0.5instead.
Show a solution
import math
def round_half_away(x):
a = abs(x)
whole = math.floor(a)
result = whole + 1 if a - whole >= 0.5 else whole
return result if x >= 0 else -resultExercise 3: Split a bill to the cent ✓ Passed
Write split_bill(total, people) where total is a Decimal amount with cents (such as Decimal('100.00')). Return a list of people shares, each a Decimal with exactly two decimal places, that add up exactly to total. Shares may differ by at most one cent, with the larger shares first.
For example, split_bill(Decimal('100.00'), 3) is [Decimal('33.34'), Decimal('33.33'), Decimal('33.33')].
from decimal import Decimal
def split_bill(total, people):
share = total / people
return [share] * people
from decimal import Decimal
def test_example():
"""100.00 split 3 ways"""
got = split_bill(Decimal('100.00'), 3)
assert got == [Decimal('33.34'), Decimal('33.33'), Decimal('33.33')], f"got {got}"
def test_sums_exactly():
"""the shares always add up to the total"""
for total, n in [('100.00', 3), ('0.05', 2), ('19.99', 7), ('1000.01', 6), ('0.00', 4)]:
shares = split_bill(Decimal(total), n)
assert len(shares) == n, f"expected {n} shares, got {len(shares)}"
assert sum(shares) == Decimal(total), f"{total} / {n}: shares {shares} sum to {sum(shares)}"
def test_two_places():
"""every share has exactly two decimal places"""
for s in split_bill(Decimal('19.99'), 7):
assert s.as_tuple().exponent == -2, f"{s!r} doesn't have two decimal places"
def test_fair():
"""shares differ by at most one cent, largest first"""
shares = split_bill(Decimal('1000.01'), 6)
assert max(shares) - min(shares) <= Decimal('0.01'), f"unfair shares: {shares}"
assert shares == sorted(shares, reverse=True), f"larger shares should come first: {shares}"
Hints (2)
- Work in whole cents (an
int), wheredivmod(cents, people)tells you the base share and how many people pay one extra cent. - Convert back with
Decimal(c) * Decimal('0.01'), then.quantize(Decimal('0.01'))to get exactly two decimal places.
Show a solution
from decimal import Decimal
def split_bill(total, people):
cents = int(total * 100)
base, extra = divmod(cents, people)
cent = Decimal('0.01')
return [(Decimal(base + (1 if i < extra else 0)) * cent).quantize(cent)
for i in range(people)]Exercise 4: Compare measurement lists ✓ Passed
Write all_close(xs, ys, rel_tol=1e-09, abs_tol=1e-12) that returns True if the two lists of floats have the same length and every pair of corresponding elements is close according to math.isclose with the given tolerances, otherwise False.
def all_close(xs, ys, rel_tol=1e-09, abs_tol=1e-12):
return xs == ys
def test_float_error():
"""tiny representation errors are tolerated"""
assert all_close([0.1 + 0.2, 0.1 * 3], [0.3, 0.3]) is True
def test_near_zero():
"""values near zero use the absolute tolerance"""
assert all_close([1e-15, 0.0], [0.0, -1e-15]) is True
def test_real_difference():
"""a genuine difference is detected"""
assert all_close([1.0, 2.0], [1.0, 2.001]) is False
def test_lengths():
"""different lengths are never close"""
assert all_close([1.0, 2.0], [1.0]) is False
def test_custom_tolerance():
"""rel_tol is passed through"""
assert all_close([100.0], [101.0], rel_tol=0.02) is True
Hints (2)
- Check the lengths first.
zipsilently stops at the shorter list. all(...)over a generator ofmath.isclose(x, y, ...)calls does the rest.
Show a solution
import math
def all_close(xs, ys, rel_tol=1e-09, abs_tol=1e-12):
if len(xs) != len(ys):
return False
return all(math.isclose(x, y, rel_tol=rel_tol, abs_tol=abs_tol)
for x, y in zip(xs, ys))