Fraction Add
Python
Medium
2 views
Problem Description
Read two fractions a/b and c/d. Create Fraction class that reduces and supports add. Output result as p q reduced.
Input Format
One line: a b c d.
Output Format
One line: p q.
Official Solution
import sys,math
p=sys.stdin.read().strip().split()
if len(p)<4: sys.exit(0)
a=int(p[0]); b=int(p[1]); c=int(p[2]); d=int(p[3])
class Fraction:
def __init__(self,p,q):
if q<0:
p=-p
q=-q
g=math.gcd(abs(p),abs(q))
self.p=p//g
self.q=q//g
def add(self,other):
return Fraction(self.p*other.q + other.p*self.q, self.q*other.q)
f1=Fraction(a,b)
f2=Fraction(c,d)
f3=f1.add(f2)
print(f'{f3.p} {f3.q}')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!