Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading