0

How can you create a Fibonacci sequence using Python?

Fibonacci

7th Aug 2016, 2:12 PM
Evans Enweremadu
Evans Enweremadu - avatar
3 Answers
+ 2
Probably not the best way, it was the first thing that came into my mind, but if you just want it to print on screen the numbers: x = 0 y = 1 max_number = 100 while y < max_number: y = x + y print(y) x = x + y print(x) Basically you store in memory two numbers, sum each with the other and print them, until the highest is bigger than a limit you specified (max_number). Note that the last numbers will be higher than max_number.
7th Aug 2016, 3:03 PM
Alberto Brandolini
Alberto Brandolini - avatar
+ 1
Also, some people like recursive functions (I don't): def fibonacci( nth) : if nth < 2: return nth else: return fibonacci( nth - 1) + fibonacci(nth - 2) This code returns the nth number in the fib sequence. If you want to print all of them you do the same as the other examples m = 1 Max = 100 while m < max: print( fibonacci(m) ) I'm testing it now and it becomes slow af after a while
7th Aug 2016, 3:56 PM
Alberto Brandolini
Alberto Brandolini - avatar
0
Another possibility is to store all the Fibonacci values into an array and add a new one based on the last two. arr = [1,1] max_length = 100 while len(arr) < max_length: arr.append( arr[len(arr) - 1] + arr[len(arr) - 2] ) for number in arr: print(number) Which may be harder to read, but follows the same principle. These are just two simple ideas, I'm sure there are better ways depending on the situation.
7th Aug 2016, 3:29 PM
Alberto Brandolini
Alberto Brandolini - avatar