我有一个可能很大的元素列表(超过100个元素):elements = [a, b, c, d, e, f, g...]

考虑到序列,我需要构建所有可能的定向循环的列表
[a,b,c,d,e], [b,c,d,e,a], [c,d,e,a,b], [d,e,a,b,c], [e,a,b,c,d]被认为是相同的,因为它们是同一有向循环的不同表示。只有起点有所不同。

另外,由于方向很重要,因此[a,b,c,d,e][e,d,c,b,a]是不同的。

我正在寻找所有长度的定向循环,从2到len(elements)。利用内置的permutationscombinations等的最优化方法,最有效的方法是什么?

最佳答案

也许我缺少了一些东西,但这对我来说似乎很简单:

def gen_oriented_cycles(xs):
    from itertools import combinations, permutations
    for length in range(2, len(xs) + 1):
        for pieces in combinations(xs, length):
            first = pieces[0],  # 1-tuple
            for rest in permutations(pieces[1:]):
                yield first + rest


然后,例如

for c in gen_oriented_cycles('abcd'):
    print c


显示:

('a', 'b')
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
('c', 'd')
('a', 'b', 'c')
('a', 'c', 'b')
('a', 'b', 'd')
('a', 'd', 'b')
('a', 'c', 'd')
('a', 'd', 'c')
('b', 'c', 'd')
('b', 'd', 'c')
('a', 'b', 'c', 'd')
('a', 'b', 'd', 'c')
('a', 'c', 'b', 'd')
('a', 'c', 'd', 'b')
('a', 'd', 'b', 'c')
('a', 'd', 'c', 'b')


是否缺少您要寻找的一些必不可少的属性?

编辑

我认为它可能缺少您的标准的这一部分:


  同样,由于方向很重要,因此[a,b,c,d,e]和[e,d,c,b,a]是不同的。


但是转而想一想,我认为它满足了该要求,因为[e,d,c,b,a][a,e,d,c,b]相同。

08-04 10:45