Created
June 8, 2016 16:40
-
-
Save iximiuz/1a830f05ae091986805ef6687ca51c36 to your computer and use it in GitHub Desktop.
Calculate binomial coefficients via Pascal's triangle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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