Using Python 3, complete the following exercise.... Exercise 5.3 (fractions.py).
ID: 3725165 • Letter: U
Question
Using Python 3, complete the following exercise....
Exercise 5.3 (fractions.py). Any fraction can be written as the division of two integers. You could express this in Python as a tuple- (numerator, denominator) For example, the fractions , and can be represented using the tuples (1 , 2), (10, 7), and (499, 10001) Write the following functions: reduce (fraction) This function takes a fraction, reduces it, and returns the result. For ex- ample, reduce(8, 4)) should return (2, 1). To reduce a fraction a/b, divide a and b by their GCD. The result is (a/d)/(b/d). The math module comes with the math.ged function add(fraction1, fraction2) Given two fractions as tuples, add them. multiply(fractioni, fraction2) Given two fractions as tuples, multiply them. divide (fraction1, fraction2) Given two fractions as tuples, divide them These functions should not use input () or print OExplanation / Answer
import math
def reduce(fraction1):
g = math.gcd(fraction1[0],fraction1[1])
return (int(fraction1[0]/g),int(fraction1[1]/g))
def add(fraction1,fraction2):
num = fraction1[0]*fraction2[1] + fraction1[1]*fraction2[0]
dem = fraction1[1]*fraction2[1]
return (num,dem)
def multipy(fraction1,fraction2):
return (fraction1[0]*fraction2[0],fraction1[1]*fraction2[1])
def divide(fraction1,fraction2):
return ((fraction1[0]*fraction2[1]),(fraction1[1]*fraction2[0]))
if __name__ == "__main__":
f1 = tuple([int(x) for x in input("Enter a fraction>>>").split("/")])
f2 = tuple([int(x) for x in input("Enter a fraction>>>").split("/")])
r1=reduce(f1)
r2=reduce(f2)
print("Reduced fraction to %d/%d and %d/%d"%(r1[0],r1[1],r2[0],r2[1]))
s = reduce(add(r1,r2))
print("Sum of the fractions: %d/%d "%(s[0],s[1]))
m = reduce(multipy(r1,r2))
print("Multiplication of the fractions: %d/%d "%(m[0],m[1]))
d = reduce(divide(r1,r2))
print("Division of the first by the second: %d/%d "%(d[0],d[1]))
I guess you need to check for the sum of the fraction. I guess the output in pic for case 1 is wrong.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.