Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I didn't manage to correct a code I thought it would work for sure. Any advice to make the code functional is accepted. Expected outputs of the following code is a list containing a cyclic permuation of the list

l = [1,2,3,4] (i.e : [[4, 1, 2, 3],[3, 4, 1, 2],[2, 3, 4, 1],[1, 2, 3, 4]])

Although what I get is : [[2, 3, 4, 1]]

The code :

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

Another variation of the solution is to consider the following code wich seems unfortunatly not working either :

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

Help me with your generous knowlege sharing please.

like image 531
melasiam Avatar asked Dec 07 '25 09:12

melasiam


1 Answers

You can use collections.deque:

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

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

Which gives you the output:

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

As mentioned in Efficient way to shift a list in python

like image 186
ceremcem Avatar answered Dec 09 '25 22:12

ceremcem