Python带限制条件的排列组合

14

我正在使用Python 3,尝试找到一种方法来获取列表的所有排列并强制执行一些限制。

例如,我有一个列表L=[1, 2, 3, 4, 5, 6, 7]

我想找到所有排列。但是,我的限制条件是:

  • 1应始终出现在2之前。
  • 3应出现在4之前,而4应出现在5之前。
  • 最后,6应出现在7之前。

当然,我可以生成所有排列,并忽略那些不符合这些约束条件的排列,但我认为这不是高效的做法。


3
你说“before”是指直接在前面吗?也就是说,[3 1 2 ...] 是合法的,但 [1 3 2 ...] 不合法(“1 应该始终在 2 前面”)。 - mathematical.coffee
不必要紧贴在前面,(1, 3, 2) 也是有效的。 - Keeto
3个回答

17
这种方法使用简单的过滤器来筛选排列。
import itertools

groups = [(1,2),(3,4,5),(6,7)]
groupdxs = [i for i, group in enumerate(groups) for j in range(len(group))]
old_combo = []
for dx_combo in itertools.permutations(groupdxs):
    if dx_combo <= old_combo: # as simple filter
        continue
    old_combo = dx_combo
    iters = [iter(group) for group in groups]
    print [next(iters[i]) for i in dx_combo]

我们正在做的是寻找一个重集合的排列。(在这种情况下,重集合是groupdxs。) 这里有一篇论文详细说明了一个O(1)算法。

1
你不需要使用permutations函数的第二个参数。这很整洁! - Katriel
3
这个(非常优雅的)方法仍然是生成所有排列然后进行过滤吗?(itertools.permutations生成的不同排列数量与给定 [1,2,3,4,5,6,7] 相同) - andrew cooke
@andrew cooke:我也这么认为。list(itertools.permutations((0,0)) -> [(0, 0), (0, 0)],即itertools.permutations()在任何情况下都会生成N!个排列。 - jfs
@andrewcook:是的,它只是过滤排列,这并不是非常高效的。但是,与直接测试更复杂的约束条件相比,它是一种更简单的过滤器。 - Steven Rumbalski
@所有人:我在我的回答中添加了一个链接,展示如何以O(1)的时间复杂度完成此操作。 - Steven Rumbalski
2
如果您使用C++中的std::next_permutation(),那么就不需要过滤器了,因为会出现多余的)在Cython中 - jfs

2
def partial_permutations(*groups):
    groups = list(filter(None, groups)) # remove empties.
    # Since we iterate over 'groups' twice, we need to
    # make an explicit copy for 3.x for this approach to work.
    if not groups:
        yield []
        return
    for group in groups:
        for pp in partial_permutations(*(
             g[1:] if g == group else g
             for g in groups
        )):
            yield [group[0]] + pp

你能举个例子说明它应该如何运行吗?(我不理解代码,而list(partial_permutations((1,2),(3,4,5),(6,7)))返回[])。 - andrew cooke
按照你尝试的方式完全运行它。在2.7.2中,它对我来说很好用。这种方法很简单:通过尝试每个组的第一个数字,然后跟随所有其他数字的排列(保持它们以相同的方式分组),递归地生成排列。 - Karl Knechtel

1

一种方法是采用其中一种交换算法,当您要将元素交换到其最终位置时,请检查它是否按正确顺序排列。下面的代码就是这样做的。

但首先让我展示它的用法:

L = [1, 2, 3, 4, 5, 6, 7]
constraints = [[1, 2], [3, 4, 5], [6, 7]]

A = list(p[:] for p in constrained_permutations(L, constraints)) # copy the permutation if you want to keep it
print(len(A))
print(["".join(map(str, p)) for p in A[:50]])

以及输出:

210
['1234567', '1234657', '1234675', '1236457', '1236475', '1236745', '1263457', '1263475', '1263745', '1267345', '1324567', '1324657', '1324675', '1326457', '1326475', '1326745', '1342567', '1342657', '1342675', '1345267', '1345627', '1345672', '1346527', '1346572', '1346257', '1346275', '1346725', '1346752', '1364527', '1364572', '1364257', '1364275', '1364725', '1364752', '1362457', '1362475', '1362745', '1367245', '1367425', '1367452', '1634527', '1634572', '1634257', '1634275', '1634725', '1634752', '1632457', '1632475', '1632745', '1637245']

但现在是代码:

def _permute(L, nexts, numbers, begin, end):
    if end == begin + 1:
        yield L
    else:
        for i in range(begin, end):
            c = L[i]
            if nexts[c][0] == numbers[c]:
                nexts[c][0] += 1
                L[begin], L[i] = L[i], L[begin]
                for p in _permute(L, nexts, numbers, begin + 1, end):
                    yield p
                L[begin], L[i] = L[i], L[begin]
                nexts[c][0] -= 1


def constrained_permutations(L, constraints):
    # warning: assumes that L has unique, hashable elements
    # constraints is a list of constraints, where each constraint is a list of elements which should appear in the permatation in that order
    # warning: constraints may not overlap!
    nexts = dict((a, [0]) for a in L)
    numbers = dict.fromkeys(L, 0) # number of each element in its constraint
    for constraint in constraints:
        for i, pos in enumerate(constraint):
            nexts[pos] = nexts[constraint[0]]
            numbers[pos] = i

    for p in _permute(L, nexts, numbers, 0, len(L)):
        yield p

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接