Search code examples
pythonlistpython-itertools

Permutations of elements of a list in Python


I have a list A. I want specific permutations such that no location is occupied by the same element more than once in a list. I present the current and expected outputs. I also want the code to work for any length of A.

from itertools import permutations

A = [1, 2, 3]

# Generate all possible permutations and convert tuples to lists
all_permutations = [list(perm) for perm in permutations(A)]

# Print the permutations
for perm in all_permutations:
    print(perm)

The current output is

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

The expected output is

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

Solution

  • Looks like you want to rotate a list by i elements for all possible values of i. Try something like this:

    A = [1, 2, 3]
    
    def rotate(a, i):
        return a[i:] + a[:i]
    
    all_rotations = [rotate(A, i) for i in range(len(A))]
    
    # Print the permutations
    for r in all_rotations:
        print(r)
    

    Output is

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

    If you want the exact output in your question ([1,2,3], [3,1,2], [2,3,1]) just rotate by -i instead of i.