Fibonacci numbers are a set of numbers where each sequential number is the sum of the previous two numbers... i.e. 1, 1, 2, 3, 5, 8, 13, etc.
I explore three different ways to code a solution.
The first solution shown below takes an input x
, and generates all fibonacci numbers between 1 and x
.
"""My first solution was to use two variables: i and j
in order to shuffle values around, and update a third value: result
which is the actual fibonacci number printed with each iteration"""
def fibo(x):
a, b, result = 0, 1, 1
# where result is the finbonacci number
# b is used to store the current finbonacci iteration while the next is calculated
# a stores the value required to calculate the next fibonacci number i..e the previous fibo number
while result <= x:
print result,
# This part temporarily stores the current fibonacci number,
# calculates the next one by adding i, and finally
# updates i so it can be used to calculate the next number if another iteration is made
b = result
result = result + a
a = b
fibo(1000)
"""Here I have removed the result variable, moved i and j into
the function definition as default values, and consolidated
the juggling of figures onto one line"""
def fibo(x, a = 0, b = 1):
while b <= x:
print b,
a, b = b, a + b
fibo(1000)
What if we wanted to produce a set number of fibonacci numbers, as opposed to all the fibo numbers up to a particular value?
def fibo(x):
# first we define a list to hold the fibonacci numbers
nums = [0,1]
# then we append the next fibonacci number to the list for the defined number of iterations x
for i in range(1, x):
# by summing the two previous numbers, which are referenced by their index
nums.append(nums[-1] + nums[-2])
# finally we print a string of the numbers from the list avoiding the starting 0 by using an index range
print " ".join(str(i) for i in nums[1:])
fibo(20)
"""This will return the nth fibonacci number"""
def fibo(n):
# these two values of n act to end the recursion of the function
# and stand as the first two fibonacci numbers as they are both 1
if n == 1 or n == 2:
return 1
# this line recursively calls the function in a factorial manner, summing the two fibonacci numbers before it
return fibo(n - 1) + fibo(n - 2)
fibo(20)
I would like to use the above recursive function to print x iterations, so I will define a separate function to do so:
def fiboPrint(x):
for i in range(1, x + 1):
print fibo(i),
fiboPrint(20)
I wish to make the output slightly more pratical for the user.
To clarify what the nth value is, I have slightly altered the FiboPrint function:
def fiboPrint(x):
for i in range(1, x + 1):
print "Iteration " + str(i) + " is: " + str(fibo(i))
fiboPrint(10)