Editor

A Fraction Class

#616 · Classes · Advanced · Find and fix · 120 XP · about 20 min

Frac(num, den) stores a fraction in lowest terms with any minus sign on the numerator, so Frac(2, 4) is stored as 1/2 and Frac(2, -4) as -1/2. A denominator of 0 raises ValueError. A Frac supports:

  • str(f), which gives text such as '-1/2', or only the numerator ('3', '0') when the denominator is 1.
  • f + g, which gives a new Frac and leaves both f and g unchanged.
  • f == g, which is True when the two fractions have the same value.

The code in the editor has two bugs. a + b gives the right answer but also changes a, and str(Frac(1, -2)) shows '1/-2' instead of '-1/2'.

Examples

str(Frac(2, 4))                # returns '1/2'
str(Frac(1, 2) + Frac(1, 3))   # returns '5/6'
str(Frac(6, -3))               # returns '-2'
Frac(1, 2) == Frac(2, 4)       # returns True
Frac(-1, 2) == Frac(1, -2)     # returns True

Constraints

  • Numerators and denominators are whole numbers from -106 to 106.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.