Project 2 · Practice

Quiz & exercises

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

Quiz

1. Why does Mod.__init__ store value % modulus instead of the value it was given?
2. What does this print?
print(2 ** 5 % 5, pow(2, 5, 5), 2 ** (5 % 5) % 5)
3. What does this print?
print(pow(3, -1, 7), 3 * pow(3, -1, 7) % 7)
4. What does this print?
class M:
    def __init__(self, v):
        self.v = v
    def __sub__(self, other):
        return self.v - other
    def __rsub__(self, other):
        return self.v - other

print(10 - M(3))
5. What does this print?
class Key:
    def __init__(self, n):
        self.n = n
    def __eq__(self, other):
        return isinstance(other, Key) and self.n == other.n
    def __hash__(self):
        return hash(self.n)
    def __iadd__(self, k):
        self.n += k
        return self

k = Key(1)
s = {k}
k += 1
print(k in s, Key(1) in s)
6. Why is it better for Mod.__eq__ to **return NotImplemented** for an incompatible operand rather than raise TypeError?
7. What does this print?
import operator

def apply(op, a, b, mod):
    return op(a, b) % mod

print(apply(operator.sub, 2, 4, 5), apply(operator.mul, 3, 4, 5))

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Goal 1: construction and representation

Write the class Mod(value, modulus):

- Both arguments must be integers, otherwise raise TypeError. The modulus must be positive, otherwise raise ValueError. - Store the residue value % modulus, so Mod(8, 3).value is 2 and Mod(-1, 5).value is 4. - value and modulus are read-only properties. - repr(Mod(8, 3)) is 'Mod(2, 3)' and int(Mod(8, 3)) is 2.

Hints (3)
  1. Validate first, then store value % modulus. Python's % already returns a non-negative result for a positive modulus, even for negative values.
  2. Store the data in _value and _modulus and expose them with @property methods that have no setter: assigning to a property without a setter raises AttributeError.
  3. int(m) calls m.__int__(), which must return an int.
Show a solution
class Mod:
    def __init__(self, value, modulus):
        if not isinstance(modulus, int):
            raise TypeError('Unsupported type for modulus')
        if not isinstance(value, int):
            raise TypeError('Unsupported type for value')
        if modulus <= 0:
            raise ValueError('Modulus must be positive')
        self._modulus = modulus
        self._value = value % modulus

    @property
    def modulus(self):
        return self._modulus

    @property
    def value(self):
        return self._value

    def __repr__(self):
        return f'Mod({self.value}, {self.modulus})'

    def __int__(self):
        return self.value

Exercise 2: Goal 2: equality, hashing and ordering

The class from goal 1 is given. Add:

- Equality by congruence: a Mod equals a Mod with the same modulus when the residues match, and equals an int congruent to it (Mod(8, 3) == 5, and also 5 == Mod(8, 3)). For a different modulus or any other type, __eq__ must return NotImplemented, so == gives False. - Hashing: congruent Mod objects with the same modulus have the same hash. - Ordering <, <=, >, >= by residue, against a Mod with the same modulus or an int (use its residue). Use functools.total_ordering; incompatible operands must lead to a TypeError.

Hints (3)
  1. Write a helper _residue(other) that returns the residue of an int, the value of a Mod with the same modulus, or None when other is incompatible. Every comparison method then starts the same way.
  2. Return NotImplemented (don't raise) for incompatible operands: then 5 == Mod(8, 3) is reflected to your __eq__, and Mod(2, 3) == 'two' quietly gives False.
  3. Defining __eq__ removes the inherited hash. Hash the same data that __eq__ uses: hash((self.value, self.modulus)). Then decorate the class with @total_ordering and write only __lt__.
Show a solution
from functools import total_ordering


@total_ordering
class Mod:
    def __init__(self, value, modulus):
        if not isinstance(modulus, int):
            raise TypeError('Unsupported type for modulus')
        if not isinstance(value, int):
            raise TypeError('Unsupported type for value')
        if modulus <= 0:
            raise ValueError('Modulus must be positive')
        self._modulus = modulus
        self._value = value % modulus

    @property
    def modulus(self):
        return self._modulus

    @property
    def value(self):
        return self._value

    def __repr__(self):
        return f'Mod({self.value}, {self.modulus})'

    def __int__(self):
        return self.value

    def _residue(self, other):
        if isinstance(other, Mod):
            return other.value if other.modulus == self.modulus else None
        if isinstance(other, int):
            return other % self.modulus
        return None

    def __eq__(self, other):
        r = self._residue(other)
        return NotImplemented if r is None else self.value == r

    def __hash__(self):
        return hash((self.value, self.modulus))

    def __lt__(self, other):
        r = self._residue(other)
        return NotImplemented if r is None else self.value < r

Exercise 3: Goal 3: arithmetic and reflected operators

Goals 1 and 2 are given. Add arithmetic that returns new Mod objects:

- +, - and * with a Mod of the same modulus or with an int, with the int on either side: Mod(2, 5) + 4, 3 + Mod(2, 5) and 3 - Mod(1, 5) (which is Mod(2, 5)) all work. - ** with an int exponent, including negative ones: Mod(3, 7) ** -1 is Mod(5, 7) (the modular inverse). A non-int exponent is unsupported. - unary -: -Mod(2, 5) is Mod(3, 5). - A different modulus or an unsupported type must raise TypeError, so return NotImplemented from your methods in those cases.

Hints (3)
  1. A generic _op(self, other, op, *, reflected=False) using operator.add, operator.sub and operator.mul avoids writing the same checks six times. Return Mod(op(a, b), self.modulus) and let the constructor reduce the result.
  2. For the reflected methods the int is the left operand: 3 - Mod(1, 5) calls Mod(1, 5).__rsub__(3) and must compute 3 - 1, not 1 - 3.
  3. For powers use the built-in pow(self.value, exp, self.modulus): it's fast, and since Python 3.8 a negative exponent gives the modular inverse. Never reduce the exponent modulo the modulus.
Show a solution
import operator
from functools import total_ordering


@total_ordering
class Mod:
    def __init__(self, value, modulus):
        if not isinstance(modulus, int):
            raise TypeError('Unsupported type for modulus')
        if not isinstance(value, int):
            raise TypeError('Unsupported type for value')
        if modulus <= 0:
            raise ValueError('Modulus must be positive')
        self._modulus = modulus
        self._value = value % modulus

    @property
    def modulus(self):
        return self._modulus

    @property
    def value(self):
        return self._value

    def __repr__(self):
        return f'Mod({self.value}, {self.modulus})'

    def __int__(self):
        return self.value

    def _residue(self, other):
        if isinstance(other, Mod):
            return other.value if other.modulus == self.modulus else None
        if isinstance(other, int):
            return other % self.modulus
        return None

    def __eq__(self, other):
        r = self._residue(other)
        return NotImplemented if r is None else self.value == r

    def __hash__(self):
        return hash((self.value, self.modulus))

    def __lt__(self, other):
        r = self._residue(other)
        return NotImplemented if r is None else self.value < r

    def _op(self, other, op, *, reflected=False):
        r = self._residue(other)
        if r is None:
            return NotImplemented
        a, b = (r, self.value) if reflected else (self.value, r)
        return Mod(op(a, b), self.modulus)

    def __add__(self, other):
        return self._op(other, operator.add)

    def __radd__(self, other):
        return self._op(other, operator.add, reflected=True)

    def __sub__(self, other):
        return self._op(other, operator.sub)

    def __rsub__(self, other):
        return self._op(other, operator.sub, reflected=True)

    def __mul__(self, other):
        return self._op(other, operator.mul)

    def __rmul__(self, other):
        return self._op(other, operator.mul, reflected=True)

    def __pow__(self, exp):
        if not isinstance(exp, int):
            return NotImplemented
        return Mod(pow(self.value, exp, self.modulus), self.modulus)

    def __neg__(self):
        return Mod(-self.value, self.modulus)

Exercise 4: Goal 4: in-place operators

Goals 1–3 are given. Add +=, -=, *= and **= so that they modify the object in place (its identity stays the same, and other names referring to it see the change). The operands allowed are the same as for the regular operators, the stored value must remain the residue, and incompatible operands must raise TypeError without changing the object.

Hints (3)
  1. __iadd__ must change self and then return self: Python rebinds the name on the left of += to whatever the method returns.
  2. Reuse your regular operators: result = self.__add__(other) is either a new Mod (copy its value into self._value) or NotImplemented (return it unchanged, and Python raises the TypeError for you).
  3. Call the method (self.__add__(other)) rather than writing self + other: the expression would raise inside __iadd__ instead of returning NotImplemented.
Show a solution
import operator
from functools import total_ordering


@total_ordering
class Mod:
    def __init__(self, value, modulus):
        if not isinstance(modulus, int):
            raise TypeError('Unsupported type for modulus')
        if not isinstance(value, int):
            raise TypeError('Unsupported type for value')
        if modulus <= 0:
            raise ValueError('Modulus must be positive')
        self._modulus = modulus
        self._value = value % modulus

    @property
    def modulus(self):
        return self._modulus

    @property
    def value(self):
        return self._value

    def __repr__(self):
        return f'Mod({self.value}, {self.modulus})'

    def __int__(self):
        return self.value

    def _residue(self, other):
        if isinstance(other, Mod):
            return other.value if other.modulus == self.modulus else None
        if isinstance(other, int):
            return other % self.modulus
        return None

    def __eq__(self, other):
        r = self._residue(other)
        return NotImplemented if r is None else self.value == r

    def __hash__(self):
        return hash((self.value, self.modulus))

    def __lt__(self, other):
        r = self._residue(other)
        return NotImplemented if r is None else self.value < r

    def _op(self, other, op, *, reflected=False):
        r = self._residue(other)
        if r is None:
            return NotImplemented
        a, b = (r, self.value) if reflected else (self.value, r)
        return Mod(op(a, b), self.modulus)

    def __add__(self, other):
        return self._op(other, operator.add)

    def __radd__(self, other):
        return self._op(other, operator.add, reflected=True)

    def __sub__(self, other):
        return self._op(other, operator.sub)

    def __rsub__(self, other):
        return self._op(other, operator.sub, reflected=True)

    def __mul__(self, other):
        return self._op(other, operator.mul)

    def __rmul__(self, other):
        return self._op(other, operator.mul, reflected=True)

    def __pow__(self, exp):
        if not isinstance(exp, int):
            return NotImplemented
        return Mod(pow(self.value, exp, self.modulus), self.modulus)

    def __neg__(self):
        return Mod(-self.value, self.modulus)

    def _iop(self, result):
        if result is NotImplemented:
            return NotImplemented
        self._value = result.value
        return self

    def __iadd__(self, other):
        return self._iop(self.__add__(other))

    def __isub__(self, other):
        return self._iop(self.__sub__(other))

    def __imul__(self, other):
        return self._iop(self.__mul__(other))

    def __ipow__(self, exp):
        return self._iop(self.__pow__(exp))