

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print first n distinct permutations of string using itertools in Python
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.
Example
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)
Output
Running the above code gives us the following result −
xxxyz xxxzy xxyxz xxyzx xxzxy xxzyx xyxxz xyxzx xyzxx xzxxy xzxyx xzyxx
- Related Questions & Answers
- Java Program to print distinct permutations of a string
- Print all distinct permutations of a given string with duplicates in C++
- Print all permutations of a given string
- Print all permutations of a string in Java
- Python Program to print all permutations of a given string
- Python Program to Print All Permutations of a String in Lexicographic Order using Recursion
- Print first m multiples of n without using any loop in Python
- Print all palindrome permutations of a string in C++
- Print distinct sorted permutations with duplicates allowed in input in C++
- All possible permutations of N lists in Python
- Print first m multiples of n in C#
- C Program to print all permutations of a given string
- All permutations of a string using iteration?
- Python Program to Print All Permutations of a String in Lexicographic Order without Recursion
- C++ Permutations of a Given String Using STL