6 examples of 'python n choose k' in Python

Every line of 'python n choose k' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
23def rchoose(n, k):
24 if 0 <= n < MAX and 0 <= k < MAX:
25 return C[n][k]
26 else:
27 return choose(n, k)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

120def choose(n, k):
121 if 0 <= k <= n:
122 ntok = 1
123 ktok = 1
124 for t in range(1, min(k, n - k) + 1):
125 ntok *= n
126 ktok *= t
127 n -= 1
128 return ntok / ktok
129 else:
130 return 0
1def choose(n, k):
2 """
3 A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
4 """
5 if 0 <= k <= n:
6 ntok = 1
7 ktok = 1
8 for t in xrange(1, min(k, n - k) + 1):
9 ntok *= n
10 ktok *= t
11 n -= 1
12 return ntok // ktok
13 else:
14 return 0
58def a_choose_b(n,k):
59 return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1)
8def log_choose(n, k):
9 r = 0.0
10 # swap for efficiency if k is more than half of n
11 if k * 2 > n:
12 k = n - k
13
14 for d in range(1,k+1):
15 r += numpy.log10(n)
16 r -= numpy.log10(d)
17 n -= 1
18
19 return r
24def __init__(self, n, k):
25 """
26 TESTS::
27
28 sage: from sage.combinat.choose_nk import ChooseNK
29 sage: c52 = ChooseNK(5,2)
30 sage: c52 == loads(dumps(c52))
31 True
32 """
33 self._n = n
34 self._k = k

Related snippets