November 3, 2017
Fibonacci numbers in Python
For definition and C++ implementation you may refer to the following post. This post reimplements it in Python.
Python code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# 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
1 2 3 4 5 6 7 8 |
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.