[Tutor] learning recursion

rakesh sharma rakeshsharma14 at hotmail.com
Sat Feb 8 06:05:03 CET 2014


Hi
Shouldn't your code be like this
def fib(n):	if n==0:		return 0	else:		return n + fib(n-1)
this works
>>> for i in range(4):	print fib(i)
	0136>>> 
> To: tutor at python.org
> From: davea at davea.name
> Date: Thu, 6 Feb 2014 18:06:41 -0500
> Subject: Re: [Tutor] learning recursion
> 
>  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
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140208/de905583/attachment-0001.html>


More information about the Tutor mailing list