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
Python program to get all permutations of size r of a string
Python's itertools.permutations() function generates all permutations of a specified length from a string. A permutation is an arrangement of elements where order matters.
Syntax
itertools.permutations(iterable, r)
Parameters:
-
iterable− The input string or sequence -
r− Length of each permutation (optional, defaults to full length)
Example
Let's generate all permutations of size 3 from the string "HELLO" ?
from itertools import permutations
def solve(s, r):
vals = list(permutations(s, r))
result = []
for x in vals:
result.append(''.join(x))
return result
s = "HELLO"
r = 3
print(solve(s, r))
['HEL', 'HEL', 'HEO', 'HLE', 'HLL', 'HLO', 'HLE', 'HLL', 'HLO', 'HOE', 'HOL', 'HOL', 'EHL', 'EHL', 'EHO', 'ELH', 'ELL', 'ELO', 'ELH', 'ELL', 'ELO', 'EOH', 'EOL', 'EOL', 'LHE', 'LHL', 'LHO', 'LEH', 'LEL', 'LEO', 'LLH', 'LLE', 'LLO', 'LOH', 'LOE', 'LOL', 'LHE', 'LHL', 'LHO', 'LEH', 'LEL', 'LEO', 'LLH', 'LLE', 'LLO', 'LOH', 'LOE', 'LOL', 'OHE', 'OHL', 'OHL', 'OEH', 'OEL', 'OEL', 'OLH', 'OLE', 'OLL', 'OLH', 'OLE', 'OLL']
How It Works
The algorithm follows these steps:
- Use
permutations(s, r)to generate all r-length permutations as tuples - Convert each tuple to a string using
''.join() - Collect all permutation strings in a list
Shorter Approach Using List Comprehension
We can simplify the solution using list comprehension ?
from itertools import permutations
def get_permutations(s, r):
return [''.join(p) for p in permutations(s, r)]
s = "ABC"
r = 2
print(get_permutations(s, r))
['AB', 'AC', 'BA', 'BC', 'CA', 'CB']
Key Points
- Permutations consider order: 'AB' and 'BA' are different
- Duplicate characters in input create duplicate permutations
- Total permutations = n!/(n-r)! where n is string length
- Returns tuples by default, use
join()to convert to strings
Conclusion
Use itertools.permutations() to generate all arrangements of r characters from a string. Convert tuples to strings using join() for readable output.
Advertisements
