python : Generating cyclic permutations code (An unexpected code error to be clarified)

标签 python algorithm python-3.x generator permutation

我没有设法更正我认为肯定会起作用的代码。接受任何使代码起作用的建议。 以下代码的预期输出是一个包含列表循环排列的列表

l = [1,2,3,4](即:[[4, 1, 2, 3],[3, 4, 1, 2],[2, 3, 4, 1] ,[1, 2, 3, 4]])

虽然我得到的是:[[2, 3, 4, 1]]

代码:

def cycGen(l):
    L=[]
    while not(l in L) :
        L.append(l)
        for i in range(len(l)):
            if l[i] == len(l) :
                l[i]=1
            else :
                l[i] = 1 + l[i] 
    return L
print(cycGen([1,2,3,4]))

解决方案的另一种变体是考虑以下代码,不幸的是,它似乎也不起作用:

def cycGen(l):
    L=[]
    for k in range(len(l)):
        L.append(l)
        for i in range(len(l)):
            if l[i] == len(l) :
                l[i]=1
            else :
                l[i] = 1 + l[i]   
    return L

请帮助我分享您慷慨的知识。

最佳答案

你可以使用collections.deque:

from collections import deque
a = [1, 2, 3, 4]

d = deque(a)
for _ in range(len(a)):
    d.rotate()
    print(list(d))

它给你输出:

[4, 1, 2, 3]
[3, 4, 1, 2]
[2, 3, 4, 1]
[1, 2, 3, 4]

Efficient way to shift a list in python 中所述

关于 python : Generating cyclic permutations code (An unexpected code error to be clarified),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24793317/

相关文章:

python - PyAudio:如何以回调/非阻塞模式访问 stream.read() 数据

Python 相当于 Perl 的 URI::Find

python - 为什么在 Python 3.6 中计算 f"\{10}"时符号 '{' 仍然存在?

python - 如何使用 python 二进制分发发送数据文件?

将点均匀放置在球体内的算法

python - 为什么我的循环在 HTML 中没有显示出好的结果?

python - Py2Exe "Missing Modules"

python - Pandas :有条件的groupby

algorithm - 在棋盘上移动 N 个国王

algorithm - 给定一个数组,你必须找到最大可能的两个相等的和