if k > n // 2:
k = n - k # more efficient and safe with smaller numbers
r = 1
- for j in range(1, k+1):
- r = r * (n-j+1) // j
+ for i in range(1, k+1):
+ r = r * (n-i+1) // i
#print("nCk%s = %i" % (str((n,k)), r))
return r
def nCkLO(n,k):
sequenceOfRank(n, len(ns), rankOfSequence(n, ns)) == ns
DOC: <http://www.site.uottawa.ca/~lucia/courses/5165-09/GenCombObj.pdf>, p.75-77
- Improved to work on k-sequence of permutations instead of only full permutations.
+ Computed from left to right to work on k-sequence of permutations
+ instead of only full permutations.
"""
try:
rank = int(rank)
return None
p = []
a = nAk(n,k)
- for i in range(1,k+1):
+ for i in range(1,k+1): # first pass from left to right
a //= n-(i-1) # optimized a = nAk(n-i, k-i)
d = rank // a # greatest multiple of a, lower or equal to r
rank = rank % a