Numeric Types · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
print(-7 // 2, -7 % 2)
2. What does this print?
print(round(2.5), round(3.5), round(-0.5))
3. Why does round(2.675, 2) return 2.67 rather than 2.68?
4. What does this print?
import math
print(0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
5. What does this print?
import math
print(math.isclose(1e-12, 0), math.isclose(1e-12, 0, abs_tol=1e-9))
6. What does this print?
import decimal
from decimal import Decimal
with decimal.localcontext() as ctx:
    ctx.prec = 3
    a = Decimal('1.23456')
    print(a, a + 0)
7. What does this print?
from decimal import Decimal
print(-7 // 2, Decimal(-7) // Decimal(2))
8. What does this print?
print(True + True, 1 == True, isinstance(False, int))
9. What does this print?
print([] or 0 or 'x', 0 and 1 / 0)
10. Which of these values is truthy?
11. What does this print?
print(int('11', 2) + int('11', 8) + int('11', 16))
12. What does this print?
from fractions import Fraction
print(Fraction(0.25) == Fraction(1, 4), Fraction(0.1) == Fraction(1, 10))

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

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.

Hints (3)
  1. divmod(n, base) gives the remaining number and the last digit in one step.
  2. Digits come out last-first, so reverse them (or insert each at the front).
  3. 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

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.

Hints (2)
  1. Work with abs(x) and put the sign back at the end.
  2. x + 0.5 can itself be rounded by floating point. Compare the fractional part a - math.floor(a) with 0.5 instead.
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 -result

Exercise 3: Split a bill to the cent

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')].

Hints (2)
  1. Work in whole cents (an int), where divmod(cents, people) tells you the base share and how many people pay one extra cent.
  2. 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

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.

Hints (2)
  1. Check the lengths first. zip silently stops at the shorter list.
  2. all(...) over a generator of math.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))