fibonacci series what Iam is missing ?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Mar 23 20:11:52 EDT 2015
On Tue, 24 Mar 2015 03:01 am, Ganesh Pal 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 ?
Python does not automatically print all return statements. If you want it to
print the intermediate values produced, you will need to add print before
each return:
py> def fib(n):
... if n == 0:
... result = 0
... elif n == 1:
... result = 1
... else:
... result = fib(n-1) + fib(n-2)
... print result, # trailing comma means no newline
... return result
...
py> fib(3)
1 0 1 1 2
2
py> fib(5)
1 0 1 1 2 1 0 1 3 1 0 1 1 2 5
5
If you want to print a list of Fibonnaci values, you need to call the
function in a loop. Removing the "print result" line again, you can do
this:
py> for i in range(6):
... print fib(i),
...
0 1 1 2 3 5
--
Steven
More information about the Python-list
mailing list