[Tutor] learning recursion

Dave Angel davea at davea.name
Fri Feb 7 00:06:41 CET 2014


 Denis Heidtmann <denis.heidtmann at gmail.com> Wrote in message:
>
> 
Please post in text, not html. Your posting program loses the
 indentation in the text view, which is what most people
 see.

Code:
def fib2(n):
	if n==1:
		return 1

	elif n==2:
		return 1
	else:
		return fib2(n-2) +fib2(n-1)

That code doesn't do anything reasonable for zero or negative
 values.  Probably what you want is

    if n==0:
        return 0
    elif n <3:
        return 1
    else:

It would probably be technically correct to raise an exception for
 n < 1, because fibonacci didn't define earlier values. But it's
 apparently acceptable to return zero for the zero
 case.




-- 
DaveA



More information about the Tutor mailing list