python - 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,然后继续第二个通配符的替换循环。我被困住了...
有什么建议么?
解决方案
您可以在这里做的是使用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
推荐阅读
- javascript - 库未导入
- java - 无法从 to 转换 - Java 的隐式类型转换和一元运算符
- python - 无法在 keras 中加载特定权重的问题
- android - Proguard 的 Admob Nativetemplates 错误
- flutter - 如何在 Flutter 2.0 上进行 dio 重试
- c# - 授予 docker 容器对 azure 存储帐户 blob 容器的访问权限
- ios - 无效更新:UITableView 部分行数无效问题
- amazon-web-services - 如何修复 Redshift db 中的历史表?
- r - 比较两个数据集的百分位数的线性回归
- reactjs - Material-UI 自动完成分组逻辑不支持重复项