Complete the Fraction class so that + adds two fractions and print shows the result in lowest terms as p/q.
What to build
A class in which + and print do the right thing.
Requirements
- Complete
__add__and__str__. - Show the result in lowest terms.
Input
Two lines, each a fraction a/b with whole numbers from 1 to 1000.
Output
The sum in lowest terms, for example 5/6.
Constraints
All numbers are from 1 to 1000.
Example
Input:
1/2
1/3
Output:
5/6
Why it works
Dividing the top and bottom by their greatest common divisor gives lowest terms, and doing it in one place means that every result is reduced.
Examples
Example 1 · Input
1/2 1/3
Expected output
5/6
Example 2 · Input
1/4 1/4
Expected output
1/2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
a/b + c/d = (a × d + c × b) / (b × d).
Hint 2
Divide top and bottom by their gcd to get lowest terms.
Hint 3
__str__ decides what print shows.
Solution
Show one correct solution (try it yourself first)
from math import gcd
class Fraction:
def __init__(self, top, bottom):
common = gcd(top, bottom)
self.top = top // common
self.bottom = bottom // common
def __add__(self, other):
return Fraction(self.top * other.bottom + other.top * self.bottom, self.bottom * other.bottom)
def __str__(self):
return f"{self.top}/{self.bottom}"
x = Fraction(*[int(v) for v in input().split("/")])
y = Fraction(*[int(v) for v in input().split("/")])
print(x + y)