Skip to content

Instantly share code, notes, and snippets.

@alanduan
Created July 19, 2012 07:48
Show Gist options
  • Save alanduan/3141433 to your computer and use it in GitHub Desktop.
Save alanduan/3141433 to your computer and use it in GitHub Desktop.
Get the nth Fibonacci number.
def f_simple_yet_stupid(n):
if n == 1 or n == 2:
return 1
return f(n - 1) + f(n - 2)
def f(n):
a = [0, 0, 1]
for i in range(n - 1):
a[:2] = a[1:]
a[2] = a[0] + a[1]
return a[2]
import time
s = time.time()
print f(100000)
print time.time() - s
@alanduan
Copy link
Author

This is also stupid. How about:

def fibonacci_generator():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

s = time.time()
for i, f in enumerate(fibonacci_generator()):
    if i == 100000:
        print f
        break
print time.time() - s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment