I'm working on question in python which deals with rational numbers, and it has a method which simplifies it. For example 12/8
gives 3/2
. I have done that question and getting the correct answer also but I have done by finding gcd of the numerator and denominator. May someone help doing it using some inbuilt special python features or functions, modules or anything unique to python as you say "The Pythonic way!"
Is there such a way or any test cases should be included to cover all possibilities?
Here is my code:
class RationalNumber:
def __init__(self, n, d=1):
self.n=n
self.d=d
'''def gcd(self, a, b): // I have taken out gcd by two methods: recursion and while loop
if b>a:
t=a
a=b
b=t
while a%b != 0:
r=a%b
a=b
b=r
return b
'''
def gcd(self, a, b):
if a%b==0:
return b
else:
return self.gcd(b, a%b)
def simplify(self):
x=self.gcd(self.n, self.d)
self.n=self.n/x
self.d=self.d/x
return RationalNumber(self.n, self.d)
def __str__(self):
print "%s/%s"%(self.n, self.d)
r1 = RationalNumber(12,8)
print r1.simplify()
When I run the program it gives the answer and gives an error:
Traceback (most recent call last):
File "C:\Python27\CTE Python Practise\New folder\RationalNumberSimplify.py", line 42, in <module>
print r1.simplify()
TypeError: __str__ returned non-string (type NoneType)
Please help me removing the error and improving the code and making it more pythonic!
Use the fraction module mentioned by @stranac. As for your other question about your error, it can be fixed by replacing the method __str__
with
def __repr__(self):
return "%s/%s"%(self.n, self.d)
For either, __str__
or __repr__
you'll need to return a string not simply print it out. It may be helpful to look over the question: