Question

I am currently new to Python and I'm not sure why i'm getting the error:

a<r raised exception RuntimeError: maximum recursion depth exceeded while calling a Python object

when I do this:

a = Rational(1,3)
r = Rational(0,5)
print(a<r)

My current code is:

class Rational:
    def _gcd(x,y):
        while y != 0:
            x, y = y, x % y
        return x

    def __init__(self, num = 0, denom = 1):
         gcd = Rational._gcd(num, denom)
         self.num = int(num / gcd)
         self.denom = int(denom / gcd)

    def __lt__(self, right):
        return Rational(self.num, self.denom) < Rational(right.num, right.denom)

It also happens for all the other relational operators when I do the same thing. Can someone enlighten me on this particular matter? How do I approach or fix this?

Thanks!

Was it helpful?

Solution

This line:

Rational(self.num, self.denom) < Rational(right.num, right.denom)

… is calling the __lt__ method again, leading to an infinite recursion. Try a different approach, assuming that we're using Python 3.x (or in Python 2.x, that from __future__ import division was executed beforehand), this should work:

self.num/self.denom < right.num/right.denom
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top