Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print first n distinct permutations of string using itertools in Python
When working with permutations of strings that contain duplicate characters, we often need to find only the distinct permutations. Python's itertools.permutations() generates all possible arrangements, including duplicates, so we need additional logic to filter unique results.
Syntax
from itertools import permutations
def get_distinct_permutations(string, n):
# Sort characters to group duplicates together
sorted_chars = sorted(list(string))
# Generate all permutations
all_perms = permutations(sorted_chars)
# Use set to store unique permutations
unique_perms = set()
count = 0
# Iterate until we find n distinct permutations
for perm in all_perms:
if count >= n:
break
perm_str = ''.join(perm)
if perm_str not in unique_perms:
unique_perms.add(perm_str)
print(perm_str)
count += 1
Example
Let's find the first 8 distinct permutations of a string with duplicate characters ?
from itertools import permutations
def get_distinct_permutations(string, n):
sorted_chars = sorted(list(string))
all_perms = permutations(sorted_chars)
unique_perms = set()
count = 0
for perm in all_perms:
if count >= n:
break
perm_str = ''.join(perm)
if perm_str not in unique_perms:
unique_perms.add(perm_str)
print(perm_str)
count += 1
# Test with string containing duplicates
string = "xyxxz"
n = 8
print(f"First {n} distinct permutations of '{string}':")
get_distinct_permutations(string, n)
First 8 distinct permutations of 'xyxxz': xxxyz xxxzy xxyxz xxyzx xxzxy xxzyx xyxxz xyxzx
How It Works
The algorithm follows these key steps:
-
Sorting:
sorted(list(string))arranges characters alphabetically, grouping duplicates together -
Permutation Generation:
permutations()creates all possible arrangements -
Duplicate Filtering: A
set()tracks already seen permutations - Counting: Stops after finding the required number of distinct permutations
Alternative Approach Using List
Instead of printing directly, you can collect the results in a list ?
from itertools import permutations
def get_distinct_permutations_list(string, n):
sorted_chars = sorted(list(string))
all_perms = permutations(sorted_chars)
unique_perms = set()
result = []
for perm in all_perms:
if len(result) >= n:
break
perm_str = ''.join(perm)
if perm_str not in unique_perms:
unique_perms.add(perm_str)
result.append(perm_str)
return result
# Example usage
string = "aab"
n = 3
distinct_perms = get_distinct_permutations_list(string, n)
print(f"Distinct permutations: {distinct_perms}")
Distinct permutations: ['aab', 'aba', 'baa']
Performance Comparison
| Approach | Memory Usage | Best For |
|---|---|---|
| Set-based filtering | Moderate | Small to medium strings |
| Mathematical approach | Lower | Large strings with many duplicates |
| Direct generation | Higher | When all permutations are needed |
Conclusion
Use itertools.permutations() with a set to filter distinct permutations efficiently. Sort the input string first to improve performance, and use a counter to limit results to the first n distinct permutations.
Advertisements
