首页 > 解决方案 > Python - 通配符生成元音

问题描述

伙计们,

通过开放课件自学python,我在作业上碰壁了。

基本上,用户键入带有 * 的单词作为元音。示例:'d*g' 表示 dig、dog 或 dug。

我编写的程序会将 * 替换为来自 object: vowels='aeiou' 的值,然后查看单词列表并查看是否匹配。示例:d*g -> *dag:不匹配,deg:不匹配,dig:匹配;结束搜索。

for char_vow in VOWELS:
  wildcard_word=word.replace('*',char_vow)
  print(wildcard_word)
  if wildcard_word in word_list:
      word=wildcard_word
      break

当有一个“*”时,这非常有效,但我的程序无法处理两个或更多。例如,如果用户输入 d**th 表示死亡,代码只会检查 daath、deeth、diith、dooth、duuth,然后返回 false。

所以我认为递归可能是答案并写出:

def wildcard_replacement(word):
    wildcard_word=""
    if word.find('*')==-1:
        return word
    else:
        for char_vow in VOWELS:
              wildcard_word=word.replace('*',char_vow,1)
              print(wildcard_word)
              if wildcard_word in word_list:
                  word=wildcard_word
                  break
              elif wildcard_word.find('*')!=-1:
                  return wildcard_replacement(wildcard_word)
        return wildcard_replacement(wildcard_word)

    print(wildcard_replacement(word))

该程序搜索:daath,daeth,daith,daoth,dauth 然后停止。事后看来,这是有道理的。不再有 *。但我希望第一个元音现在从 a 翻转到和 e,然后继续第二个通配符的替换循环。我被困住了...

有什么建议么?

标签: pythonstringrecursionreplace

解决方案


您可以在这里做的是使用itertools 产品,您可以指定示例中所需的元音组合,然后我们death可以2设置repeat = 2并获取所有 2 个元音字母组合,然后我们可以用元音组合str.replace替换'**'直到我们得到了一场比赛wordbank

from itertools import product

vowels = 'aeiou'
wordbank = ['death']
word = 'd**th'
x = word.count('*')

l = [''.join(i) for i in [*product(vowels, repeat = x)]]
print(l)

for i in l:
    guess = word.replace('**', i)
    if guess in wordbank:
        print(guess)
        break
 death

推荐阅读