how to get distinct permutations of a set in python

To get the distinct permutations of a set in Python, we can use the permutations() function from the itertools module. We can then convert the resulting iterator of tuples to a set to remove duplicates. Here's an example:

main.py
from itertools import permutations

my_set = {'a', 'b', 'c'}
perms = set(permutations(my_set))

print(perms)
109 chars
7 lines

Output:

main.py
{('c', 'b', 'a'), ('a', 'b', 'c'), ('a', 'c', 'b'), ('c', 'a', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a')}
103 chars
2 lines

Note that the permutations() function returns tuples instead of sets, which is why we convert it to a set to remove duplicates.

gistlibby LogSnag