如何获得字符串(元音或辅音)的组合?

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

给定指数的可能组合数 例如单词 BANANA 的索引 [0] 应该给我 :

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

输出:

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

期望的输出:

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

您可以根据给定单词的索引,向前创建组合。

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

这将为您提供列表列表作为组合索引。

输出:

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

您不需要组合,您可以使用 slicesrange.

非常轻松地生成从特定索引开始的前缀
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)]

(显然,如果您需要 set,您可以更改为 return { ... }

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

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

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