Different ways of Fibonacci generation using Python
One of the most oft-cited coding questions especially in internship interviews is for the Fibonacci sequence. Here i provide different type of ways to generate Fibonacci numbers in Python including a generator
def fib_r(n):
#print n
if (n == 0): return(0)
if (n == 1): return(1)
return(fib_r(n-1) + fib_r(n-2))
def fibBinet(n):
phi = (1 + 5**0.5)/2.0
return int(round((phi**n - (1-phi)**n) / 5**0.5))
def fib_dp(n):
l = [0,1]
for i in range(2,n+1):
l.append(l[i-1]+l[i-2])
return l[n]
def fib_ultimate(n):
if n==0: return 0
a,b = 0,1
for i in range(n-1):
a,b = b,a+b
return b
def fib_gen():
a, b = 0, 1
while True: # First iteration:
yield a # yield 0 to start with and then
a, b = b, a + b # a will now be 1, and b will also be 1, (0 + 1)