-1

Here is my original function.

def f(n):
    if n<0:
        print("Error.Bad input")
    elif n==0:
        return 1
    elif n==1:
        return 1
    else:
        return f(n-1)+f(n-2)

Is it possible to modify Fibonacci Python function so that not only does it have to calculate f(n) but also it prints f(0), f(1), f(2),....,f(n) in the function?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
HTH
  • 1
  • I suggest you to do some research before posting questions. Refer: http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python Even if this doesn't help, you'll find several other in same or different languages doing exactly what you need to do. – Sambhav Sharma Dec 10 '15 at 07:33

4 Answers4

0

Instead of using a recursive function you could do this:

def f(n):
    if n < 0:
        print("Error.Bad input")
    elif n <= 1:
        return 1
    else:
        result = [1, 2]
        print(1)
        print(2)
        for i in range(n - 2):
            result = [result[1], result[0] + result[1]]
            print(result[1])
        return result[1]
Dav
  • 26
  • 1
0
def fib(n):
    pred, curr = 0, 1
    k = 1
    while (k<n):
        pred, curr = curr, curr + pred
        print(curr)
        k = k + 1
Tunaki
  • 125,519
  • 44
  • 317
  • 399
Rana
  • 1
  • 1
0

Probably the optimal "pythonic" way to create a sequence (a list) of fibonacci numbers of arbitraly size n is to define a function which does so, than to call that function with size as an input argument. For example:

def fibonacci_sequence(n):
    x = [0, 1]
    [x.append(x[-1] + x[-2]) for i in range(n - len(x))]
    return x

fibonacci_sequence(15)

The result is:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
episteme
  • 1
  • 1
0

Bottom-up approach. Complexity is O(n):

def fib(n):
    if n in (1, 2):
        return 1

    i = z = 1

    for _ in range(3, n+1):
        z, i = i + z, z

    return z