50 XP

70. Simplify a fraction

Intermediate math

A fraction is in its lowest terms when no whole number bigger than 1 divides both its top and its bottom: 6/8 is 3/4 in lowest terms. The largest number that divides both is their greatest common divisor, and dividing both by it gives the lowest terms in one step.

Write a function reduce_fraction(numerator, denominator) that takes the top and bottom of a fraction and returns it in lowest terms as a list [top, bottom]:

  • The bottom is always positive: a minus sign goes on top. 6/-8 becomes [-3, 4], and -6/-8 becomes [3, 4].
  • A fraction worth 0 is written [0, 1].
  • A whole number has a bottom of 1: 10/5 becomes [2, 1].

Example 1

Inputnumerator = 6, denominator = 8
Output[3, 4]
Explanation2 divides both 6 and 8.

Example 2

Inputnumerator = 6, denominator = -8
Output[-3, 4]
ExplanationThe minus sign moves to the top.

Example 3

Inputnumerator = 0, denominator = 5
Output[0, 1]
ExplanationZero is always written 0/1.

Constraints

  • numerator is a whole number from -10^9 to 10^9.
  • denominator is a whole number from -10^9 to 10^9, but never 0.

Submit also runs 11 more tests you can't see.

Practises Numbers and Math (lesson 3).

Code
def reduce_fraction(numerator, denominator):
    """Write a fraction in lowest terms.

    numerator: int, the top
    denominator: int, the bottom, never 0
    Returns: list of two ints, [top, bottom], in lowest
        terms with bottom > 0
    """
    # Write your code here
    pass