Skip to content

Instantly share code, notes, and snippets.

@Deathnerd
Created February 27, 2016 18:11
Show Gist options
  • Save Deathnerd/156360b5311d5c000ee1 to your computer and use it in GitHub Desktop.
Save Deathnerd/156360b5311d5c000ee1 to your computer and use it in GitHub Desktop.
from math import factorial
def binomial_coefficient(n, k):
"""
Find the binomial coefficient of nCk. This is space efficient
because it doesn't store the entire Pascal's Triangle; only the
current row you're working on.
:param n:
:param k:
:return:
"""
# We only need to store up to k integers for the row of
# Pascal's Triangle
b = [0 for _ in range(k + 1)]
b[0] = 1
for i in range(1, n + 1):
# start at the last integer (up to the kth one)
# of the last row and calculate the new row
j = min(i, k)
while j > 0:
b[j] += b[j - 1]
j -= 1
# We've found nCk
return b[k]
def no_couples(n):
total = 0
for k in range(0, n + 1):
# (nCk)*2^k*(2n-k)!*(-1)^k
total += binomial_coefficient(n, k) * 2 ** k * factorial(2 * n - k) * (-1) ** k
return total
from timeit import timeit
def time_wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
print timeit(time_wrapper(no_couples, 10), number=10000)
from math import factorial
def nCk(n, k):
return factorial(n) / (factorial(k) * factorial(n - k))
def noCouples(n):
total = 0
for k in range(0, n + 1):
total += nCk(n, k) * 2 ** k * factorial(2 * n - k) * (-1) ** (k)
return total
from timeit import timeit
def time_wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
print timeit(time_wrapper(noCouples, 10), number=10000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment