我没有设法更正我认为肯定会起作用的代码。接受任何使代码起作用的建议。 以下代码的预期输出是一个包含列表循环排列的列表
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]
关于 python : Generating cyclic permutations code (An unexpected code error to be clarified),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24793317/