python – 查找元音替换的所有组合

我试图找到一个单词中所有元音的所有可能组合.所以举个例子”你好’:

[halla,halle,halli,hallo,hallu,hella,halle,halli,hallo,hallu ……]

我编写了以下函数,它将只取每个元音,并在每个元音,它将只用元音替换它们并将每个版本添加到列表中.我试图将其改变为我想要的排列,但它不起作用.我尝试在追加后插入元音(“”.join(string),arr),但这会导致无限递归.

def vowels(word, arr=None):
    if arr is None:
        a = []

    for i, c in enumerate(word):
        if c in 'aeiou':
            for v in 'aeiou':
                string = list(word)
                string[i] = v
                arr.append("".join(string))
    return arr

有没有人有什么建议?

最佳答案 一旦错误的CristopheD提到修复,你的函数返回:

['hallo', 'hello', 'hillo', 'hollo', 'hullo', 'hella', 'helle', 'helli', 'hello', 'hellu']

…所以它返回了一些可能的组合,但不是全部.

这是因为它依次取出单词中的每个元音,并依次用每个元音替换它,然后继续单词中的下一个元音 – 但不考虑它在后续元音中发现的前一个元音.这是一个递归解决方案,适用于具有任意数量元音的单词:

import re

VOWELS = "aeiou"
RE_VOWEL = re.compile("[%s]" % VOWELS)

def helper(parts):
    if len(parts) == 1:
        yield parts[0]
    else:
        for vowel in VOWELS:
            for item in helper([vowel.join(parts[:2])] + parts[2:]):
                yield item

def vowels(word):
    parts = re.split(RE_VOWEL, word)
    return list(helper(parts))
点赞