您可以使用来自 itertools 配方 here 的这个配方:
def nth_combination(iterable, r, index):
'Equivalent to list(combinations(iterable, r))[index]'
pool = tuple(iterable)
n = len(pool)
if r < 0 or r > n:
raise ValueError
c = 1
k = min(r, n-r)
for i in range(1, k+1):
c = c * (n - k + i) // i
if index < 0:
index += c
if index < 0 or index >= c:
raise IndexError
result = []
while r:
c, n, r = c*r//n, n-1, r-1
while index >= c:
index -= c
c, n = c*(n-r)//n, n-1
result.append(pool[-1-n])
return tuple(result)
示例用法:
>>> nth_combination(range(7), 3, 5)
(0, 2, 3)
>>> nth_combination(range(7), 3, 34)
(4, 5, 6)
反转:
from math import factorial
def get_comb_index(comb, n):
k = len(comb)
rv = 0
curr_item = 0
n -= 1
for offset, item in enumerate(comb, 1):
while curr_item < item:
rv += factorial(n-curr_item)//factorial(k-offset)//factorial(n+offset-curr_item-k)
curr_item += 1
curr_item += 1
return rv
示例用法:
>>> get_comb_index((4,5,6), 7)
34
>>> get_comb_index((0,1,2), 7)
0
>>> get_comb_index((0,2,4), 7)
6