Permutation of a number of objects is the representation of how the updates can be present in different sequences. But sometimes we may have two objects in a series of given objects which are identical. In that case two sequences will become equal. In this article will see how to represent only the unique sequences from a given list of objects.
The module itertools have a method called permutations which help us achieve this. To get the unique permutations we take help of the set method which stores only the distinct elements. But before that we get the elements in the sorted order using the sorted method.
In the below program K is the maximum number of unique elements we want to display out of entire possible unique permutations.Using a while loop we keep adding the unique element to the final list we want to display only if it is not already added in the set.
from itertools import permutations def permutation_value(str, k): s = sorted(list(str)) p = permutations(s) m = 0 set_1 = set() str = '' while m < k: str = ''.join(p.__next__()) if str not in set_1: set_1.add(str) print(str) m += 1 str = "xyxxz" i = 12 permutation_value(str, i)
Running the above code gives us the following result −
xxxyz xxxzy xxyxz xxyzx xxzxy xxzyx xyxxz xyxzx xyzxx xzxxy xzxyx xzyxx