【问题标题】:How to get the combinations of a string (vowel or consonant)?如何获得字符串(元音或辅音)的组合?
【发布时间】:2023-03-22 01:42:01
【问题描述】:

给定指数的可能组合数 例如单词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'}

【问题讨论】:

  • 您不需要组合并减少结果。这只是一些 prefix_sum 变体。问题是索引的用途 - 目前尚不清楚。
  • 是的,你是对的@DanielHao,谢谢指出

标签: python-3.x combinations itertools


【解决方案1】:

您不需要组合,您可以使用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']

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 2017-10-21
      • 2021-12-24
      • 2020-08-19
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多