csc major boy
csc major boy

Reputation: 13

Fibonacci function list

I am currently doing a part of my assignment i have to make it so if the user enters 10 in function the answer should be

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

but my program results in

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

This is my program

def fib(n):
    fibonacci = []
    a = 0
    b = 1
    for i in range(n):
        fibonacci.append(b)
        a, b = b, a+b
    return fibonacci

Upvotes: 1

Views: 2705

Answers (1)

sberry
sberry

Reputation: 132018

You just need to append a instead of b.

def fib(n):
    fibonacci = []
    a = 0
    b = 1
    for i in range(n):
        fibonacci.append(a)
        a, b = b, a+b
    return fibonacci

Results for print(fib(10))

> python fib.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Upvotes: 5

Related Questions