Fibonacci series recursion error

Gary Herron gherron at islandtraining.com
Sat Apr 30 05:41:52 CEST 2011


On 04/29/2011 08:22 PM, lalit wrote:
> import os
> def fib(n):
> 	if n == 1:
>            return(n)
> 	else:
>            return (fib(n-1)+fib(n-2))
>
> list=fib(20)
> print(list)
>
> The above function return the
> return (fib(n-1)+fib(n-2))
>
>
> RuntimeError: maximum recursion depth exceeded in comparison
> [36355 refs]
>
> can any one help

You correctly test for n==1, but what about when n==2?    When the 
recursion works its way down to fib(2), you call both fib(1) and fib(0), 
but the latter starts an infinite sequence of calls to fib(-1), fib(-2) 
and so on without end.

Gary Herron




More information about the Python-list mailing list