Skip to content

Instantly share code, notes, and snippets.

@iximiuz
Created June 8, 2016 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iximiuz/1a830f05ae091986805ef6687ca51c36 to your computer and use it in GitHub Desktop.
Save iximiuz/1a830f05ae091986805ef6687ca51c36 to your computer and use it in GitHub Desktop.
Calculate binomial coefficients via Pascal's triangle
def next_row(prev_row):
row = [prev_row[0]] * (len(prev_row) + 1)
for idx in range(len(prev_row) - 1):
row[idx + 1] = (prev_row[idx] + prev_row[idx + 1])
return row
def binomial(n, k, cache=None):
""" Calculates binomial coefficients using Pascal's triangle.
0 1
1 1 1
2 1 2 1
3 1 3 3 1
4 1 4 6 4 1
...
Use `cache` for reusing previous calculation results.
"""
if k == 0 or k == n:
return 1
if k == 1 or k == n - 1:
return n
cache = cache or [[1]]
while len(cache) <= n:
cache.append(next_row(cache[-1]))
return cache[n][k]
if __name__ == '__main__':
c = None # = [] uncomment it to speed up execution.
for n in range(150):
for k in range(n + 1):
print('n={n}, k={k} -> {b}'.format(n=n, k=k, b=binomial(n, k, c)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment