Use objects and classes to reduce a rational number in Python. A rational number should be stored in __numer and __denom. Then a function called counting(self, number): with this function number should be added to the current Rational number. After it should update the self.__numer and self.__denom variables to the sum of self and number. As well a reduce() method should be called to put the Rational in lowest terms; however this method should not return anything.
Program Code Screenshot
Sample Output
Program Code to Copy
class Rational:
def __init__(self,num,den):
self.__numer = num
self.__denom = den
def counting(self,number):
#Calculate numerator and denominator
self.__numer =
self.__numer*number.__denom+self.__denom*number.__numer
self.__denom = self.__denom*number.__denom
#Find the GCD of 2 numbers
def gcd(a,b):
if b==0:
return a
return Rational.gcd(b,a%b)
def reduce(self):
#Find the GCD. Reduce numerator and denominator by gcd
g = Rational.gcd(self.__numer,self.__denom)
self.__numer = self.__numer//g
self.__denom = self.__denom//g
def __str__(self):
return str(self.__numer)+'/'+str(self.__denom)
if __name__ == '__main__':
a = Rational(2,3)
b = Rational(5,6)
print('a = '+str(a))
print('b = '+str(b))
a.counting(b)
print('a + b = '+str(a))
a.reduce()
print('After reducing the result : '+str(a))
Get Answers For Free
Most questions answered within 1 hours.