LIONEL JOSEPH
LIONEL JOSEPH

Reputation: 43

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'}

Upvotes: 3

Views: 359

Answers (2)

blueteeth
blueteeth

Reputation: 3565

You don't need combinations, and you can generate prefixes starting at a specific index pretty easily using slices and range.

from typing import List

def get_parts(word: str, start: int) -> List[str]:
    return [word[start:i] for i in range(start + 1, len(word) + 1)]

(Obviously you can change to return { ... } if you need it to be a set.

>>> get_parts("BANANA", 0)
['B', 'BA', 'BAN', 'BANA', 'BANAN', 'BANANA']

>>> get_parts("BANANA", 2)
['N', 'NA', 'NAN', 'NANA']

>>> get_parts("BANANA", 4)
['N', 'NA']

Upvotes: 2

Chandella07
Chandella07

Reputation: 2117

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']

Upvotes: 1

Related Questions