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

时间:2018-08-19 22:58:36

标签: 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)

3 个答案:

答案 0 :(得分:1)

一种快速解决方案:

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)次,这不是您想要的输出。

答案 1 :(得分:0)

您可以使用product中的repeatitertools函数来生成元音组合。不仅仅是为每个组合生成单词:

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

答案 2 :(得分:0)

使用递归加生成器:

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)