In: Computer Science
7.
Fractions
You can express a fraction as a list: [numerator,
denominator]. For example
1
2
can
be expressed as the list [1,2].
(a) Write a function called
factionAdd()
that takes two fractions as lists and adds
them. For example, fraction([1,2], [3,4]) returns
[5,4]
(b) Write a function
fractionMult()
that multiplies two fractions that are
passed
as lists.
[HINT: You may use the following function
gcd
(
x
;
y
) to help you calculate the
Greatest Common Divisor, which you will need to reduce
fractions to the simplest
form.]
def gcd(x, y):
"""To calculate the greatest common divisor of x and
y"""
x1 = abs(min(x, y))
y1 = abs(max(x, y))
gcd_ = x1
if y1 % x1:
gcd_ = gcd(x1, y1 % x1)
Code Screenshot :
Executable Code:
#Function to find the greatest common
divisor
def gcd(x, y):
#Find the absolute values
x1 = abs(min(x, y))
y1 = abs(max(x, y))
gcd_ = x1
#Computing the GCD
if y1 % x1:
gcd_ = gcd(x1, y1 % x1)
#Return the result
return gcd_
#Function to multiply fractions
def fractionMult(a,b):
mul = (a[0]*b[0],a[1]*b[1])
gcd_mul = gcd(mul[0],mul[1])
#Finding the simplest form
simplest_form= [mul[0]/gcd_mul,mul[1]/gcd_mul]
#Return the result
return simplest_form
#Function to add fractions
def fractionAdd(a,b):
gcd_ab = gcd(a[1],b[1])
m_a = b[1]/gcd_ab;
m_b = a[1]/gcd_ab;
sum = ((a[0]*m_a) + (b[0]*m_b),(gcd_ab*m_a*m_b))
gcd_sum = gcd(sum[0],sum[1])
#Finding the simplest form
simplest_form = [sum[0]/gcd_sum,sum[1]/gcd_sum]
#Return the result
return simplest_form
#Prompting the user for input
n1 = int(input("Enter numerator for fraction 1: "))
d1 = int(input("Enter denominator for fraction 1: "))
n2 = int(input("Enter numerator for fraction 2: "))
d2 = int(input("Enter denominator for fraction 2: "))
#Printing the result
print("Addition of Fractions :",fractionAdd([n1,d1],[n2,d2]))
print("Product of Fractions :",fractionMult([n1,d1],[n2,d2]))
Sample Output :
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)