Search code examples
python-3.xcombinationspython-itertools

How to get the combinations of a string (vowel or consonant)?


Number of possible combinations for the given Indices for example the indice[0] of the word BANANA should give me :

{'B',
 'BA',
 'BAN',
 'BANA',
 'BANAN',
 'BANANA'}
word='BANANA'
indices=[0,2,4]
def find_combinations(word:str,indices:list):
    a=[''.join(l) for i in range(len(word)) for l in combinations(word, i+1)]
    b=[x for x in a if x.startswith('B')]
    return b

output:

set(b)
{'B',
 'BA',
 'BAA',
 'BAAA',
 'BAAN',
 'BAANA',
 'BAN',
 'BANA',
 'BANAA',
 'BANAN',
 'BANANA',
 'BANN',
 'BANNA',
 'BN',
 'BNA',
 'BNAA',
 'BNAN',
 'BNANA',
 'BNN',
 'BNNA'}

desired output:

{'B',
 'BA',
 'BAN',
 'BANA',
 'BANAN',
 'BANANA'}

Solution

  • You can create the combinations, based on index on a given word, forward way.

    word = "BANANA"
    indice = [0,2,4]
    
    def find_comb(word:str, indice:list):
        final = []
        for i in indice:
            local = []
            new = ""
            for j in word[i:]:
                new = new + j
                local.append(new)
            final.append(local)
        return final
    
    print(*find_comb(word, indice), sep='\n')
    

    This will give you list of lists as combinations index wise.

    Output:

    ['B', 'BA', 'BAN', 'BANA', 'BANAN', 'BANANA']
    ['N', 'NA', 'NAN', 'NANA']
    ['N', 'NA']