A Rational Number Class

medium
Unit 13 · Decorators & Classes0/3 to milestone

Implement Rational(num, den=1) without the fractions module:

  • always stored in lowest terms with a positive denominator (Rational(2, -4) is -1/2); a zero denominator raises ZeroDivisionError
  • + - * / with other Rationals and ints (both sides), unary -, abs
  • ==, < (and the other comparisons via functools.total_ordering), hash consistent with equality (Rational(2, 1) == 2 and they hash the same)
  • str → "3/4", or just "3" when the denominator is 1; float(r)
#classes#maths#dunder-methods2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
A Rational Number Class · TechGradify