Open In App

Python - All Position Character Combination

Last Updated : 17 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To generate all position character combinations from a string we need to create combinations of characters from the string where each combination is formed by selecting characters at different positions. We can use functions like combinations() from itertools or custom loop approach. For Example lets suppose we are having a string s="abc" we need to find the

Using itertools.combinations

We can use combinations() from the itertools module to generate all combinations of characters from the string.

Python
import itertools

# Input string
s = "abc"

# Generate all combinations of characters at different positions
c = []
for r in range(1, len(s) + 1):  # r is the size of each combination
    c.extend(itertools.combinations(s, r))

# Convert tuples to strings for display
c = [''.join(comb) for comb in c]

print(c) 

Output
['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']

Explanation:

  • itertools.combinations(s, r) function generates all combinations of length r from the string s. We loop through all possible values of r (from 1 to the length of the string) to get all combinations.
  • extend() adds the combinations to the list combinations.

Using a Nested Loop (for a custom combination)

We can also manually create combinations with nested loops. Here's how to do it:

Python
s = "abc"
c = []

# Generate combinations using nested loops
for i in range(len(s)):
    for j in range(i+1, len(s)+1):
        c.append(s[i:j])

print(c) 

Output
['a', 'ab', 'abc', 'b', 'bc', 'c']

Explanation:

  • Outer loop sets the start position of the combination, and the inner loop iterates through the substring that starts from the outer loop's index to create all possible combinations.
  • Combinations.append(s[i:j]) stores each valid combination.

Next Article
Practice Tags :

Similar Reads