0

so I have to make a thing for school, but I can't figure it out. So I have to get the first 30 numbers of the Fibonacci sequence using arrays. The code should be simple, and mine looks something like this.

fib = [0, 1] * 15
for i in range(30):
    fib = fib[i-1] + fib[i-2]
    print(fib)

Any input is appreciated!

wogsland
  • 9,106
  • 19
  • 57
  • 93
Gloopjuice
  • 29
  • 4

3 Answers3

0

What you have is fairly close with some modification, that is, the Fibonacci sequence starts with 1, 1 not 0, 1 and you need to store the result of each calculation for the next:

fib = [1]*30
for i in range(2, 30):
    fib[i] = fib[i-1] + fib[i-2]
    print(fib[i])
wogsland
  • 9,106
  • 19
  • 57
  • 93
0

A generator is ideal for this exercise.

Try this:

def fibonacci(n):
    a = 0
    b = 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(list(fibonacci(30)))

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

I think you can just use this:

fib = [0, 1]
for i in range(1,30):
    fib.append(fib[i] + fib[i-1])
print(fib)

The changes I have made is to append each fib number to the list. This is important for the list to update. Before you had nothing to change or add digits to the list. Then I just took the sum of the last number on the list (fib[i] not fib[i-1]) and the same with the second to last number on the list(fib[i-1] not fib[i-2])

Jerry_V
  • 61
  • 6