Skip to content

Instantly share code, notes, and snippets.

@anemochore
Created February 5, 2017 17:18
Show Gist options
  • Save anemochore/156e930f7b420c9ae05db7c9fab9d488 to your computer and use it in GitHub Desktop.
Save anemochore/156e930f7b420c9ae05db7c9fab9d488 to your computer and use it in GitHub Desktop.
crude combination solution with dynamic programming
def factorial(n):
if factorial_array[n] > -1:
return factorial_array[n]
else:
factorial_array[n-1] = factorial(n - 1)
return n * factorial_array[n-1]
def combination(n, k):
if k == 0 or n == k:
return 1
else:
return int(factorial(n) / factorial(k) / factorial(n - k))
a = input().split(' ')
if not a[0].isdigit() or len(a) == 1 or not a[1].isdigit():
print('both n and k should be numbers')
quit()
n, k = int(a[0]), int(a[1])
if n < 0 or k < 0:
print('both n and k should be >= 0')
quit()
factorial_array = [1]
factorial_array = factorial_array + [-1] * n #fill list with -1 n times
for n2 in range(n + 1):
for k2 in range(n2 + 1):
print("{0}C{1} = {2}".format(n2, k2, combination(n2, k2)), end=" ")
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment