Open In App

Python – All Position Character Combination

Last Updated : 07 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a character K, append to each index and all lengths combinations.

Input : test_str = ‘gfg’, K = ‘$’ Output : [‘gfg’, ‘gf$’, ‘g$g’, ‘g$$’, ‘$fg’, ‘$f$’, ‘$$g’, ‘$$$’] Explanation : All possible pairs with replacement occurrences. Input : test_str = ‘gfg’, K = ‘*’ Output : [‘gfg’, ‘gf*’, ‘g*g’, ‘g**’, ‘*fg’, ‘*f*’, ‘**g’, ‘***’] Explanation : All possible pairs with replacement occurrences.

Method #1 : Using loop + zip() + join() + product()

In this, the task of forming combination is done using product(), loop is used for iteration of elements, join() used to get the desired result and zip() used to combine each extracted product with original String.

Python3




# Python3 code to demonstrate working of
# All Position Character Combination
# Using loop + zip() + join() + product()
import itertools
 
# initializing strings
test_str = 'gfg'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "$"
 
res = []
 
# True and false represent Character from String and K respectively.
for sub in itertools.product((True, False), repeat = len(test_str)):
    res.append("".join(chr if ele else K for chr, ele in zip(test_str, sub)))
 
# printing result
print("The required Combinations : " + str(res))


Output:

The original string is : gfg
The required Combinations : ['gfg', 'gf$', 'g$g', 'g$$', '$fg', '$f$', '$$g', '$$$']

Method #2 : Using list comprehension

This is similar to above method, the only difference being it’s a shorthand all the functionality in a single line.

Python3




# Python3 code to demonstrate working of
# All Position Character Combination
# Using list comprehension
import itertools
 
# initializing strings
test_str = 'abc'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "$"
 
# one liner to perform this task
res = ["".join(chr if ele else K for chr, ele in zip(test_str, sub)) \
     for sub in itertools.product((True, False), repeat = len(test_str))]
 
# printing result
print("The required Combinations : " + str(res))


Output:

The original string is : abc
The required Combinations : ['abc', 'ab$', 'a$c', 'a$$', '$bc', '$b$', '$$c', '$$$']

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n2)

Space Complexity: O(n)

Method#3: Using Recursive method.

Algorithm:

  1. Define a recursive function all_combinations that takes the input string test_str and special character K as inputs.
  2. Check if the length of the input string is zero, return an empty string.
  3. Take the first character of the input string as first_char and the remaining string as rest_str.
  4. Recursively call the all_combinations function on the rest_str to get combinations without the first character.
  5. Recursively call the all_combinations function on the rest_str to get combinations with the first character.
  6. Add the first_char to each combination obtained in step 5 and store it in with_first_char.
  7. Recursively call the all_combinations function on the rest_str to get combinations with the special character K.
  8. Add the special character K to each combination obtained in step 7 and store it in with_K.
  9. Merge all the results from step 4, 6, and 8 to obtain all possible combinations of the input string with special character K.
  10. Define another recursive function length_combinations that takes the list of combinations res, desired length length, 
  11. current index index, and an empty list new_lst as inputs.
  12. Check if the current index is equal to the length of the input list, return new_lst.
  13. Check if the length of the current element of the input list is equal to the desired length, append it to the new_lst.
  14. Recursively call the length_combinations function with the incremented index and updated new_lst.
  15. Call the all_combinations function with input string and special character as test_str and K respectively.
  16. Call the length_combinations function with the output of the all_combinations function and the length of the input string as inputs.
  17. Print the resulting list obtained in step 15.

Python3




def all_combinations(test_str, K):
    if len(test_str) == 0:
        return ['']
     
    first_char = test_str[0]
    rest_str = test_str[1:]
     
    # recursive call to get combinations without the first character
    without_first_char = all_combinations(rest_str, K)
     
    # recursive call to get combinations with the first character
    with_first_char = all_combinations(rest_str, K)
    with_first_char = [first_char + x for x in with_first_char]
     
    # recursive call to get combinations with special character
    with_K = all_combinations(rest_str, K)
    with_K = [K + x for x in with_K]
     
    # merging all results
    return without_first_char + with_first_char + with_K
def length_combinations(test_str,length,index=0,new_lst=[]):
  if len(test_str)==index:return new_lst
  if len(test_str[index])==length:
    new_lst.append(test_str[index])
  return length_combinations(test_str,length,index+1,new_lst)
# initializing strings
test_str = 'abc'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "$"
 
# one liner to perform this task
res = all_combinations(test_str,K)
res=length_combinations(res,len(test_str))
# printing result
print("The required Combinations : " + str(res))


Output

The original string is : abc
The required Combinations : ['abc', 'ab$', 'a$c', 'a$$', '$bc', '$b$', '$$c', '$$$']

Time Complexity:
The time complexity of the all_combinations function is O(2^n), where n is the length of the input string. This is because the function generates all possible combinations of the input string by recursively calling itself twice (with and without the current character) for each character in the input string.
The time complexity of the length_combinations function is O(n), where n is the length of the input list. This is because the function iterates through the list of combinations once and performs a constant amount of work for each element.
Therefore, the overall time complexity of the algorithm is O(2^n).

Auxiliary Space:

The space complexity of the all_combinations function is O(2^n), where n is the length of the input string. This is because at each recursive call, the function creates two new lists to store the combinations with and without the current character, and a third list to store combinations with the special character. Since the function is called n times (once for each character in the input string), the total space used by these lists is 2^n.

The space complexity of the length_combinations function is O(m), where m is the number of combinations of length n in the input list. This is because the function creates a new list to store only the combinations of the desired length. The worst-case scenario is when all combinations have the desired length, in which case the space used by the new list is m.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads