fibonacci series what Iam is missing ?

Chris Angelico rosuav at gmail.com
Mon Mar 23 12:16:48 EDT 2015


On Tue, Mar 24, 2015 at 3:01 AM, Ganesh Pal <ganesh1pal at gmail.com> wrote:
> Hello team ,
>
>
> [root at localhost Python]# cat  fibonacci-Sequence-3.py
>
> ## Example 2: Using recursion
> def fib(n):
>     if n == 0:
>         return 0
>     elif n == 1:
>         return 1
>     else:
>         return fib(n-1) + fib(n-2)
> print fib(5)
>
> # python  fibonacci-Sequence-3.py
> 5
>
> what Iam I missing in the program , I was expecting 0,1,1,2,3 ?

What you're doing is printing out the fifth Fibonacci number. So there
are three things to note:

1) To display the entire sequence, you will need some sort of loop.
2) Your algorithm is about as hopelessly inefficient as it could
possibly be, barring deliberate intent. [1]
3) You are running Python 2.x; unless you have a good reason not to,
it's better to use Python 3.
4) You're running as root. Normally, something like this should be run
as a regular user - it's safer that way.

Err, *amongst* the things to note are such diverse elements as...
etcetera, etcetera. Ahem.

I would suggest rewriting this as a much more straight-forward loop;
begin at the beginning, go on till you reach the point you wanted,
then stop.

ChrisA

[1] Cue the demonstration of a worse version from someone's student?



More information about the Python-list mailing list