python fibbonacci sequence code example
Example 1: fibonacci sequence python
def fib(num):
"""return the number at index `num` in the fibonacci sequence"""
if num <= 2:
return 1
return fib(num - 1) + fib(num - 2)
def fib2(num):
a, b = 1, 1
for _ in range(num - 1):
a, b = b, a + b
return a
print(fib(6))
print(fib2(6))
Example 2: python fibonacci generator
def fib(num):
a = 0
b = 1
for i in range(num):
yield a
temp = a
a = b
b = temp + b
for x in fib(100):
print(x)
def fib2(num):
a = 0
b = 1
result = []
for i in range(num):
result.append(a)
temp = a
a = b
b = temp + b
return result
print(fib2(100))