-2

I want to caculate an church number by python below,but it prompt the errors when I use the input greater than 993,anyone whom had the experience told me what happend?

NUM0=lambda f: lambda x:x
SUCC=lambda n: lambda f: lambda x: f(n(f)(x))

def decoding(n):
    num=NUM0
    for i in xrange(n):
        num = SUCC(num)
    return num

def encoding(num):
    f=lambda x:x+1
    return str(num(f)(0))

print encoding(decoding(994)) # Why fails once greater than 993
Mr.ke
  • 65
  • 1
  • 9
  • 6
    The error traceback tells you exactly *"what happened"*: `maximum recursion depth exceeded`. What don't you understand? Have you read e.g. [this](http://stackoverflow.com/q/3323001/3001761)? – jonrsharpe Sep 11 '14 at 15:09
  • 2
    [`sys.getrecursionlimit`](https://docs.python.org/2/library/sys.html#sys.getrecursionlimit), [`sys.setrecursionlimit`](https://docs.python.org/2/library/sys.html#sys.setrecursionlimit) – falsetru Sep 11 '14 at 15:10
  • Python crashes intentionally when the call stack contains one thousand functions. This is so potentially infinite recursive calls don't gobble up all your available memory, or cause a far nastier crash on the C implementation level. – Kevin Sep 11 '14 at 15:11
  • Fair,so an maximum recursion depth exist in python and can not be configured? – Mr.ke Sep 11 '14 at 15:12
  • It can't be removed, but it can be raised. See falsetru's comment. – Kevin Sep 11 '14 at 15:12
  • Thanks,Kevin & Falsetru, It solve my doubt:-) – Mr.ke Sep 11 '14 at 15:15

1 Answers1

1

You get a maximum recursion depth exceeded because python tries to protect itself against possible infinite recursive calls. Basically it stops itself in order not to cause a crash that could be a lot worse.

You can change the recursion limit with sys.setrecursionlimit (as said by @falsetru).

But as @ThomasWouters said in this answer:

Doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big."

Community
  • 1
  • 1
t.pimentel
  • 1,465
  • 3
  • 17
  • 24