how to get all permutations of a set in python

To get all the permutations of a set in Python, you can use the permutations function from the itertools module.

Here's an example:

main.py
from itertools import permutations

my_set = {1, 2, 3}

# Get all permutations of the set
perms = permutations(my_set)

# Print each permutation
for perm in perms:
    print(list(perm))
186 chars
11 lines

Output:

main.py
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
60 chars
7 lines

In the example above, we first import the permutations function from the itertools module. We then create a set called my_set with the values 1, 2, and 3. We call the permutations function on my_set to get all permutations of the set. We then loop through each permutation and print it.

Note that the permutations function returns an iterator, so we use the list function to convert each permutation to a list before printing it.

gistlibby LogSnag