amrrs
amrrs

Reputation: 6325

Fibonacci series in python 3 displays only final number

I'm a beginner for Python and trying to print Fibonacci series recursively. When i try this, the return function doesn't print at all, hence just the argument that i pass gets printed.

Here's the code:

def fibR(n):
 if n == 1 or n ==2:
    return (1)
 return(fibR(n-1) + fibR(n-2))
print(fibR(5))

Can someone help me to get all the numbers in the series?

Upvotes: 0

Views: 336

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49318

A basic (but not naïve) recursive Fibonacci solution is as follows:

>>> def fib(num, first=0, second=1):
...     if not num: return second
...     return fib(num-1, second, first+second)
...
>>> fib(5)
8

You can save the intermediate values in two ways: create a list and append() to it, or have your function return a tuple.

Method 1:

>>> def fibl(num, first=0, second=1):
...     results.append(second)
...     if not num: return
...     return fibl(num-1, second, first+second)
...
>>> results = []
>>> fibl(5)
>>> results
[1, 1, 2, 3, 5, 8]

Method 2:

>>> def fibr(num, first=0, second=1, *results):
...     if not num: return results+(second,)
...     return fibr(num-1, second, first+second, *(results + (second,)))
...
>>> fibr(5)
(1, 1, 2, 3, 5, 8)

Upvotes: 0

rlbond
rlbond

Reputation: 67749

The inefficient way to do this is to use a loop:

def fibR(n):
    if n == 1 or n ==2:
        return 1
    return fibR(n-1) + fibR(n-2)

for i in range(1,6):
    print(fibR(i))

However, this is inefficient because it will calculate the lower Fibonacci numbers more than once. You can use an array to store the intermediate Fibonacci numbers and improve performance:

def fibR(n):
    if n > len(fibR.values) - 1:
        for i in range(len(fibR.values), n+1):
            fibR.values.append(fibR(i-2) + fibR(i-1))
    return fibR.values[n]

fibR.values = [0, 1, 1]
for i in range(1,6):
    print(fibR(i))

Upvotes: 3

Related Questions