Uncategorized

Simple lambda expressions in python but occurs error ‘maximum recursion depth exceeded in comparison’


This is my code.

def div_by_primes_under(n):
    checker = lambda x: False
    i = 2
    while i <= n:
        if not checker(i):
            # checker = (lambda f, i: lambda x: x % i == 0 or f(x))(checker, i) 
            checker = lambda x: (x % i == 0 or checker(x))
        i = i + 1
    return checker

print(div_by_primes_under(10)(12))
print(div_by_primes_under(10)(121))

And the error information seems to be

Traceback (most recent call last):
  File "hw2.py", line 106, in <module>
    print(div_by_primes_under(10)(12))
  File "hw2.py", line 102, in <lambda>
    checker = lambda x: (x % i == 0 or checker(x))
  File "hw2.py", line 102, in <lambda>
    checker = lambda x: (x % i == 0 or checker(x))
  File "hw2.py", line 102, in <lambda>
    checker = lambda x: (x % i == 0 or checker(x))
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded in comparison

I modified it with the a nested lambda expression, which seems to have the same function as the former(the line that was annotated). The error message disappear and it runs as expected.

I wonder if this is related to the principles of Python interpreters.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *