Skip to content

Instantly share code, notes, and snippets.

@lucemia
Created August 14, 2015 16:01
Show Gist options
  • Save lucemia/29e187f6ee64dcdda955 to your computer and use it in GitHub Desktop.
Save lucemia/29e187f6ee64dcdda955 to your computer and use it in GitHub Desktop.
combination.py
def c(n, r):
print n, r
if r == 1: return n
if n == r: return 1
return c(n-1, r) + c(n-1, r-1)
# can compute it on time
print c(5, 2)
# cannot finish it ontime
# or stack will overflow
c(999, 33)
# use cache to speed up
cache = {}
def c1(n, r):
if r == 1: return n
if n == r: return 1
if (n,r) in cache:
return cache[(n,r)]
v = c1(n-1, r) + c1(n-1, r-1)
cache[(n,r)] = v
return v
print c1(999, 33)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment