Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 permutations with tuples that contain duplicates

I want to create all the possible combinations of a tuple with duplicate elements.

For example lets say that we have {3,3,0}. I want the code to return: (3,3,0) (3,0,3) (0,3,3)

I looked at itertools documentation and at numerous stack overflow questions but i did not find a answer to this.

How can I implement it? Or, can this be implemented in general?

like image 926
George Sp Avatar asked Dec 05 '25 01:12

George Sp


2 Answers

You could use permutations from itertools and then use a set to remove any doubles:

result = set(permutations((3, 3, 0)))
like image 161
Mureinik Avatar answered Dec 07 '25 17:12

Mureinik


Using more_itertools, a third-party library:

> pip install more_itertools

Code

import more_itertools as mit


iterable = (3, 3, 0)
list(mit.distinct_permutations(iterable))
# [(3, 3, 0), (3, 0, 3), (0, 3, 3)]

See more_itertools docs for details.

like image 29
pylang Avatar answered Dec 07 '25 16:12

pylang