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
Program to find list of all possible combinations of letters of a given string s in Python
Sometimes we need to find all possible combinations of letters from a given string. This problem involves generating all non-empty subsequences of characters while maintaining lexicographical order when duplicates exist.
So, if the input is like s = "pqr", then the output will be ['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']
Algorithm Approach
To solve this, we will follow these steps ?
- Create an empty result list
- Iterate through the string from right to left
- For each character, combine it with all existing combinations
- Add the character itself as a new combination
Implementation
Let us see the following implementation to get better understanding ?
def solve(s):
st_arr = []
for i in range(len(s) - 1, -1, -1):
# Create combinations with current character and existing combinations
for j in range(len(st_arr)):
st_arr.append(s[i] + st_arr[j])
# Add the current character as a single combination
st_arr.append(s[i])
return st_arr
s = "pqr"
print(solve(s))
The output of the above code is ?
['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']
How It Works
The algorithm processes the string from right to left. For each character:
- Step 1: Start with character 'r' ? result: ['r']
- Step 2: Process 'q' ? combine with 'r' to get 'qr', add 'q' ? result: ['r', 'qr', 'q']
- Step 3: Process 'p' ? combine with existing combinations ? result: ['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']
Alternative Approach Using itertools
Python's itertools module provides a more concise solution ?
from itertools import combinations
def solve_itertools(s):
result = []
# Generate combinations of all possible lengths
for length in range(1, len(s) + 1):
for combo in combinations(s, length):
result.append(''.join(combo))
return result
s = "pqr"
print(solve_itertools(s))
The output of the above code is ?
['p', 'q', 'r', 'pq', 'pr', 'qr', 'pqr']
Comparison
| Method | Order | Complexity | Best For |
|---|---|---|---|
| Manual Algorithm | Custom order | O(2^n) | Specific ordering requirements |
| itertools.combinations | Lexicographical | O(2^n) | Standard combinations |
Conclusion
The manual approach builds combinations incrementally from right to left, while itertools provides a cleaner solution with lexicographical ordering. Choose based on your specific ordering requirements.
---