Fraction Class Difficulty: HARD
Problem Statement
Suggest Edit
Problem Statement
if f1 = 1/4 and f2 = 3/5
f1.add(f2); results in:
f1 = 17/20 and f2 = 3/5
if f1 = 1/4 and f2 = 3/5
f1.multiply(f2); results in:
f1 = 3/20 and f2 = 3/5
if f1=5/20, which can be further simplified as 1/4 so this
simplify will perform this.
The first line of input contains two space-separated integer values, which represent numerator and denominator.
The second line of input contains an integer N representing queries to define how many times the operation must occur.
Next, N lines contain 3 space-separated integers representing the type of query, numerator, and denominator.
Print the value of the fraction after every query in a separate line.
1 <= numerator <= 100
1 <=denominator <= 100
1 <= N <= 15
type = 1 or 2
67 14
1
2 7 78
67/156
Fist fraction is 67/14 and no. of queries is 1. So now
in the next line 2 7 8 means type=2 which defines
multiplication and second fraction is 7/78 so 67/74 * 7/78=67/156.
47 71
3
1 91 78
2 67 75
1 36 74
779/426
52193/31950
2506241/1182150
Given fraction is 47/71 and no. of queries is 3. So now in the next 3 lines 1 91 78 means type = 1 which defines addition and second fraction is 91/78 so 47/71 + 91/78= 779/426.
Next query is 2 67 75 means type=2 which defines multiplication and second fraction is 67/75 so 52193/31950 * 67/75= 52193/31950.
Last query is 1 36 74 means type=1 which defines addition and second fraction is 36/74 so 52193/31950 + 36/74 = 2506241/1182150.
import math class Fraction: def __init__(self,num,den): self.num=num self.den=den def printer(self): print(str(self.num)+'/'+str(self.den)) #Create your fraction class here. def add(self,f2): self.num=self.num*f2.den+self.den*f2.num self.den=self.den*f2.den def multiply(self,f2): self.num*=f2.num self.den*=f2.den def simplify(self): gcd1=math.gcd(self.num,self.den) self.num=int(self.num/gcd1) self.den=int(self.den/gcd1) a,b = input().split() queries=int(input()) f1=Fraction(int(a),int(b)) for i in range(queries): dec,c,d = input().split() f2=Fraction(int(c),int(d)) if int(dec)==1: f1.add(f2) f1.simplify() f1.printer() else: f1.multiply(f2) f1.simplify() f1.printer()
Comments
Post a Comment