Optimising a fibonacci sequence generator python

Krios101

I am trying to create a program which creates a Fibonacci sequence up to the value of the sequence being 200. I have the basic set up down where I can compute the sequence but I wish to display it in a certain way and I have forgotten how to achieve this.

I wish to write the numbers to an array which I have defined as empty initially, compute the numbers and assign them to the array and print said array. In my code below the computation is ok but when printed to screen, the array shows the value 233 which is above 200 and not what I'm looking for. I wish to print all the values under 200 which I've stored in an array.

Is there a better way to initially define the array for what I want and what is the correct way to print the array at the end with all elements below 200?

Code follows:

#This program calculates the fibonacci sequence up to the value of 200
import numpy as np


x = np.empty(14, float) #Ideally creates an empty array to deposit the fibonacci numbers in
f = 0.0 #Dummy variable to be edited in the while loop

#Here the first two values of the sequence are defined alongside a counter starting at i = 1
x[0] = 0.0
x[1] = 1.0
i = 1

#While loop which computes the values and writes them to the array x
while f <= 200:
  f = x[i]+x[i-1] #calculates the sequence element
  i += 1 #Increases the iteration counter by 1 for each loop
  x[i] = f #set the array element equal to the calculated sequence number

print(x)

For reference here is a quick terminal output, Ideally I wish to remove the last element:

[   0.    1.    1.    2.    3.    5.    8.   13.   21.   34.   55.   89.
144.  233.]
Dr Xorile

There are a number of stylistic points here. Firstly, you should probably use integers, rather than floats. Secondly, you should simply append each number to a list, rather than pre-define an array of a particular size.

Here's an interactive session:

>>> a=[0,1]
>>> while True:
        b=a[-1]+a[-2]
        if b<=200:
            a.append(b)
        else:
            break
>>> a
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related