Skip to main content
 首页 » 编程设计

python之在 Python 中列出给定 n 个元素的所有定向循环的最有效方法

2025年05月04日15arxive

我有一个可能非常大的元素列表(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) .利用内置 permutations 的优化来实现它的最 pythonic 方法是什么? , combinations等等?

请您参考如下方法:

也许我遗漏了什么,但这对我来说似乎很简单:

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') 

是否缺少您正在寻找的一些基本属性?

编辑

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

Also, since direction matters, [a,b,c,d,e] and [e,d,c,b,a] are different.

但转念一想,我认为它符合该要求,因为 [e,d,c,b,a] 与 [a,e,d,c,b ] 给你。