Fibonacci numbers in Python

For definition and C++ implementation you may refer to the following post. This post reimplements it in Python.

Fibonacci numbers

Python code

# N             = 0 1 2 3 4 5 6 7
# Fibonacci (N) = 0 1 1 2 3 5 8 13
def Fibonacci (N): 

   # Initial case is 0 by definition
   if N == 0:
      return 0

   # Save the first two Fibonacci numbers
   x = 1
   y = 1

   # Keep updating the last two Fibonacci numbers
   # to calculate the next one
   for i in range(3, N+1):
      sum =  x + y
      x = y
      y = sum

   return y

# Example
for n in range (0, 8):
   print "Fiboncci({}) = {}".format(n, Fibonacci(n)) 

If you run the code snippet above you should get the output below

Fiboncci(0) = 0
Fiboncci(1) = 1
Fiboncci(2) = 1
Fiboncci(3) = 2
Fiboncci(4) = 3
Fiboncci(5) = 5
Fiboncci(6) = 8
Fiboncci(7) = 13

If you have comments ? questions ? pease use the comments section below. Thanks for reading.

Tags:

Leave a Reply