[Tutor] learning recursion

Peter Otten __peter__ at web.de
Thu Feb 6 20:45:06 CET 2014


Denis Heidtmann wrote:

> Running python 2.7 on Ubuntu 12.04
> 
> Code:
> def fib2(n):
> if n==1:
> return 1
> elif n==2:
> return 1
> else:
> return fib2(n-2) +fib2(n-1)
> 
> The above works:
> 
>>>> fib2(7)
> 13
>>>> fib2(4)
> 3
> 
>>>> for i in range(4):
> ...     print fib2(i)
> ...
> 
> The above results in an error:
> 
> Traceback (most recent call last):
>   File "<stdin>", line 2, in <module>
>   File "testing.py", line 21, in fib2
>     return fib2(n-2) +fib2(n-1)
>   File "testing.py", line 21, in fib2
>     return fib2(n-2) +fib2(n-1)
> 
> <snip>
> 
>  File "testing.py", line 21, in fib2
>     return fib2(n-2) +fib2(n-1)
> RuntimeError: maximum recursion depth exceeded
>>>>
> 
> Is this some subtle problem or is it some stupid mistake on my part?

Try to figure out how fib2(0) is evaluated.



More information about the Tutor mailing list