Skip to content

Instantly share code, notes, and snippets.

@wolf0403
Created July 6, 2014 05:15
Show Gist options
  • Save wolf0403/1862fa91a64e7b831d18 to your computer and use it in GitHub Desktop.
Save wolf0403/1862fa91a64e7b831d18 to your computer and use it in GitHub Desktop.
Different ways of fib() in Python
N=30
PRINT = False
def f1(n):
if n < 2: return n
return f1(n-1) + f1(n-2)
print f1(N) if PRINT
def f2(n, mem={}):
if n < 2: return n
r = mem.get(n, f2(n-1, mem) + f2(n-2, mem))
mem[n] = r
return r
print f2(N) if PRINT
def f3(n, mem):
mem[0] = 0
mem[1] = 1
for i in range(2, n+1):
mem[i] = mem[i-1] + mem[i-2]
return mem[n]
print f3(N, [0]*(N+1)) if PRINT
def f4(n):
i, j = 0, 1
for _ in range(n-1):
i, j = j, i+j
return j
print f4(N) if PRINT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment