70. Simplify a fraction
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
numerator = 6, denominator = 8[3, 4]Example 2
numerator = 6, denominator = -8[-3, 4]Example 3
numerator = 0, denominator = 5[0, 1]Constraints
numeratoris a whole number from -10^9 to 10^9.denominatoris 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).
math.gcd(a, b)gives the greatest common divisor of two whole numbers. It is never negative, even for negative numbers.- Divide both parts by it with
//, which keeps whole numbers (/would give floats like 3.0). - If the bottom is then negative, flip the signs of both parts. A top of 0 needs no special case:
math.gcd(0, d)is the size ofd, so 0/5 becomes 0/1, and 0/-3 becomes 0/-1, then 0/1 after the flip.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.