In: Computer Science
For python
Write a new method for the Fraction class called mixed() which returns a string that writes out the Fraction in mixed number form. Here are some examples: f1 = Fraction(1, 2) print(f1.mixed()) # should print "1/2" f2 = Fraction(3, 2) print(f2.mixed()) # should return "1 and 1/2" f3 = Fraction(5, 1) print(f3.mixed()) # should return "5" def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, top, bottom): self.num = top # the numerator is on top self.den = bottom # the denominator is on the bottom def __str__(self): return str(self.num) + "/" + str(self.den) def simplify(self): common = gcd(self.num, self.den) self.num = self.num // common self.den = self.den // common def __add__(self,otherfraction): newnum = self.num*otherfraction.den + self.den*otherfraction.num newden = self.den * otherfraction.den f = Fraction(newnum, newden) f.simplify() return( f ) # define the mixed() method below def main(): if __name__ == "__main__": main()
Short Summary:
Implemented the program as per requirement
Attached source code and sample output
**************Please do upvote to appreciate our time. Thank you!******************
Source Code:
def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
from math import floor
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
def simplify(self):
common = gcd(self.num, self.den)
self.num = self.num
self.den = self.den
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den +
self.den*otherfraction.num
newden = self.den * otherfraction.den
f = Fraction(newnum, newden)
f.simplify()
return( f )
def mixed(self):
s= self.num/self.den
a=str(s)
b=a.split(".")
if int(b[1]) is not 0:
number=float("." + b[1])
# Fetch integral value of the decimal
intVal = floor(number)
# Fetch fractional part of the decimal
fVal = number - intVal
# Consider precision value to
# convert fractional part to
# integral equivalent
pVal = 1000000000
# Calculate GCD of integral
# equivalent of fractional
# part and precision value
gcdVal = gcd(round(fVal * pVal), pVal)
# Calculate num and deno
num= round(fVal * pVal) // gcdVal
deno = pVal // gcdVal
# Print the fraction
if int(b[0])>0:
print("The value is ",b[0]," and ",(intVal * deno) + num, "/",
deno)
else:
print("The value is ",self.num, "/", self.den)
else:
print("The value is ",b[0])
def main():
f1 = Fraction(3,2)
f1.mixed()
if __name__ == "__main__":
main()
Output:
For 3,2,
For 5,1,
For 1,2,
**************Please do upvote to appreciate our time.
Thank you!******************