Python - Character repetition string combinations

When generating string combinations with character repetition, we need to create all possible arrangements where each position can contain any character from the original string. This is essentially generating permutations with repetition using recursive backtracking.

Example

Below is a demonstration of generating all permutations with repetition ?

def to_string(my_list):
    return ''.join(my_list)

def lex_recurrence(my_string, my_data, last_val, index_val):
    length = len(my_string)
    
    for i in range(length):
        my_data[index_val] = my_string[i]
        
        if index_val == last_val:
            print(to_string(my_data))
        else:
            lex_recurrence(my_string, my_data, last_val, index_val + 1)

def all_lex(my_string):
    length = len(my_string)
    my_data = [""] * length
    my_string = sorted(my_string)
    lex_recurrence(my_string, my_data, length - 1, 0)

my_string = "MQ"
print("The string is:")
print(my_string)
print("All permutations with repetition of " + my_string + " are...")
all_lex(my_string)
The string is:
MQ
All permutations with repetition of MQ are...
MM
MQ
QM
QQ

How It Works

The algorithm uses recursive backtracking to generate combinations ?

  • to_string() ? Converts a list of characters into a string by joining them
  • lex_recurrence() ? Recursively fills each position with every possible character from the input string
  • all_lex() ? Sets up the data structure and initiates the recursive process

Using itertools.product()

Python's itertools module provides a simpler approach for generating permutations with repetition ?

import itertools

my_string = "MQ"
length = len(my_string)

print("The string is:")
print(my_string)
print("All permutations with repetition of " + my_string + " are...")

for combination in itertools.product(my_string, repeat=length):
    print(''.join(combination))
The string is:
MQ
All permutations with repetition of MQ are...
MM
MQ
QM
QQ

Comparison

Method Code Complexity Performance Best For
Recursive High Good Learning algorithms
itertools.product() Low Optimized Production code

Conclusion

The recursive approach demonstrates the underlying algorithm for generating permutations with repetition. For practical applications, use itertools.product() as it's more concise and optimized.

Updated on: 2026-03-26T03:04:34+05:30

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements