Find/store the first 50 terms of the Fibonacci sequence via Looping

Viewed 400

I am trying find and store the first 50 elements of the Fibonacci Sequence into an array by looping. I am quite new to Python and I can't get past this point, I am very frustrated that I can't figure out how to do this.

My code so far:

x=51
 def Fibonacci(x):
    First_Value=0
    Second_Value=1
    for i in range(x):
        Next_value = First_Value
        First_Value = Second_Value
        Second_Value = Next_value + Second_Value
    return Fist_Value"

But I can't figure out how to print this in an array where I have to show the first 50 values.

3 Answers

You can define an empty list (or array) at the beginning of the function, and then add to it on every iteration of the for loop.

Here's an example

def Fibonacci(x):
    fib_array = [None]*x
    First_Value=0
    Second_Value=1
    for i in range(x):
        Next_value = First_Value
        First_Value = Second_Value
        Second_Value = Next_value + Second_Value
        fib_array[i] = First_Value
    return fib_array

Fibonacci(10)

Output

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

Since you alrady know how to generate Fibonacci numbers then one solution is to simply generate an array out of your predefined function:

result = [Fibonacci(x) for x in range(51)]

but this is awefuly inefficient (you recalculate Fibonacci numbers all the time). You can improve it by tweaking your function:

def Fibonacci(x):
    if x < 0:
        raise ValueError("Argument has to be a nonnegative integer")
    if x == 0:
        return []
    if x == 1:
        return [0]
    result = [0, 1]
    for _ in range(x-2, 0, -1):
        result.append(result[-1] + result[-2])
    return result

print(Fibonacci(51))

Your code can be modified to return an array.

def Fibonacci(x):
   First_Value=0
   Second_Value=1
   Result = []
   for i in range(x):
       Next_value = First_Value
       First_Value = Second_Value
       Second_Value = Next_value + Second_Value
       Result.append(Next_value)
   return Result

print(Fibonacci(20))

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

Related