繁体   English   中英

有序列表的可逆组合生成器

[英]Invertible combination generator for ordered lists

我有代码,其中给出了一个有序整数列表,我生成了几个新列表,并且我需要能够将这些列表与从 1 到 N 选择 k(或 0 到(N 选择 k)之间的整数一一对应)- 1)在python中)。

例如,如果我有一个 N=7,k=3,那么我可能会从列表 [0,1,2] 开始,我可能会枚举 0。然后我生成列表 [0,1,3], [ 0,1,5] 和 [3,4,6],它们都需要由 0,...,34 范围内的整数唯一标识。

我知道我可以使用 itertools 来生成有序列表,

itertools.combinations(range(7), 3)

但我需要一个反函数,它比简单地搜索预先生成的列表更有效,因为我将使用大 N 并且每个列表引用大约 50 个新列表。

您可以在此处使用 itertools 配方中的配方:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM