Python:查找所有以元音代替星号的单词

2024-09-28 05:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到一个列表,列出所有可能有元音的单词,星号在哪里。例如:对于字符串“ppl”,程序应返回一个包含“appla”、“apple”、“appli”、“applo”、“applu”、“eppla”、“epple”、…、“upplu”的列表。你知道吗

下面的程序只返回:['appl*'、'eppl*'、'ippl*'、'oppl*'、'uppl*'、'uppla'、'upple'、'uppli'、'upplo'、'upplu']。你知道吗

VOWELS = 'aeiou'


def find_words (word):
    # find the positions of the asterisks and put them into a list
    listFromWord = list(word)
    wilds = []
    for i, x in enumerate(listFromWord):
        if x == '*':
            wilds.append(i)

    # find all words with vowels at the indexes and put them into a list       
    possibleWords = []
    possibleWord = list(word)
    for i in wilds:
        for letter in VOWELS:
            possibleWord[i] = letter          
            possibleWords.append(''.join(possibleWord))

    return(possibleWords)

a = find_words('*ppl*')
print(a)

Tags: thein程序列表forfindppllist
3条回答

一个快速解决方案:

VOWELS = 'aeiou'


def find_words (word):
    # find the positions of the asterisks and put them into a list
    listFromWord = list(word)
    wilds = []
    for i, x in enumerate(listFromWord):
        if x == '*':
            wilds.append(i)

    # find all words with vowels at the indexes and put them into a list       
    possibleWords = []
    possibleWord = list(word)
    for i in wilds:
        for letter in VOWELS:
            possibleWord[i] = letter   
            if '*' in possibleWord:
                possibleWords += find_words(''.join(possibleWord))
            else:
                possibleWords.append(''.join(possibleWord))

    return(possibleWords)

a = find_words('*ppl*')
print(a)

# ['appla', 'apple', 'appli', 'applo', 'applu', 'eppla', 'epple', 'eppli', 'epplo', 'epplu', 'ippla', 'ipple', 'ippli', 'ipplo', 'ipplu', 'oppla', 'opple', 'oppli', 'opplo', 'opplu', 'uppla', 'upple', 'uppli', 'upplo', 'upplu', 'uppla', 'upple', 'uppli', 'upplo', 'upplu']

您的程序只迭代len(wilds)*len(VOWELS)次,这不是您想要的输出。你知道吗

您可以使用来自itertoolsproductrepeat函数来生成元音组合。而不仅仅是为每个组合生成单词:

from itertools import product, repeat

VOWELS = 'aeiou'


def find_words(word):
    result = [word.replace('*', '{}').format(*x)
              for x in product(*repeat(VOWELS, word.count('*')))]
    return result


print(find_words('*ppl*'))

输出:

['appla', 'apple', 'appli', 'applo', 'applu', 'eppla', 'epple', 'eppli', 'epplo', 'epplu', 'ippla', 'ipple', 'ippli', 'ipplo', 'ipplu', 'oppla', 'opple', 'oppli', 'opplo', 'opplu', 'uppla', 'upple', 'uppli', 'upplo', 'upplu']

使用递归+生成器:

VOWELS = "aeiou"
def words(s):
    if s:
        for w in words(s[1:]):
            if s[0] == '*':
                for v in VOWELS:
                    yield v + w
            else:
                yield s[0] + w
    else:
        yield ''

for a_word in words("*ppl*"):
    print(a_word)

相关问题 更多 >

    热门问题