Home > other >  Get every combination of the insertion of a character in a string
Get every combination of the insertion of a character in a string

Time:12-09

For reference you can also see see this question: I am trying to finding every possible combination of adding a character to a string

Exactly as the other question I'm trying to get every single possible combination of the insertion of a character inside a string.

I don't understand how to implement the solution, specially how to get every combination of bits.

string = 'abc'

def generate_string(string):
    number_of_combinations = 2**(len(string)-1)
    str = ''
    configurations = []
    for i in range(number_of_combinations):
        #somehow get a true/false configuration of dashes
        #with abc i should have 8 possible configurations
        #i would append every configuration to configurations list
        
        for char in string:
            str = str   char
            #if the first char of configuration is true then add a '-', if false do nothing and so on for every char in the string

Can someone help me ?

CodePudding user response:

This should do it:

import itertools as itl

init = 'abcde' #Base str
inst = 'z' #Char to be inserted

for i in itl.combinations_with_replacement(init[:-1], len(init)-1):
    #Compute every combination of strs that can be computed from init
    instAfter = list(set(i)) #Remove duplicates
    newStr = '' #prepare result str
    for i in init: #loop over init str
        newStr = newStr   i #Add char to result str
        if i in instAfter: #If char in instAfter add the insert char
            newStr = newStr   inst
    print(newStr)
  • Related