我想得到一个列表,列出所有可能有元音的单词,星号在哪里。例如:对于字符串“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)
一个快速解决方案:
您的程序只迭代
len(wilds)*len(VOWELS)
次,这不是您想要的输出。你知道吗您可以使用来自
itertools
的product
和repeat
函数来生成元音组合。而不仅仅是为每个组合生成单词:输出:
使用递归+生成器:
相关问题 更多 >
编程相关推荐