Fibonacci series recursion error
harrismh777
harrismh777 at charter.net
Sat Apr 30 00:45:30 EDT 2011
lalit wrote:
> The above function return the
> return (fib(n-1)+fib(n-2))
>
> RuntimeError: maximum recursion depth exceeded in comparison
> [36355 refs]
There is much debate about this generally, but general wisdom is that
recursion is to be avoided when possible. Another way to say this is,
"Only use recursion when there is no other obvious way to handle the
problem".
Recursion is very tempting to young artists because its a ~cool trick,
and because sometimes it requires very little coding (although huge
amounts of memory!), or as in your case, recursion depth errors.
Anyway, the better way to build a Fibonacci sequence generator is the
following... I have expanded things a bit so that someone not knowing
what the sequence is can see what is happening... you will notice simple
'for' iterations, and no recursion:
===============begin======================
def fib(i=1):
l=[]
p=0
a=1
n=p+a
for j in range(1,i+1):
l.append(a)
p=a
a=n
n=p+a
for j in l:
print(j, end=' ')
fib(7)
=======================end======================
kind regards,
m harris
More information about the Python-list
mailing list