gpt4 book ai didi

python - 弦乐变奏

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:32 25 4
gpt4 key购买 nike

我在 python 中有一个字符串和一个“规则”字典,或者可能对字符串进行的更改。例如,一个规则可能有一个关键字 'he' 和一个值 'e',或者一个关键字 'll''l' 的值。

这些规则意味着我的字符串中出现的任何“他”都可以用 “e” 替换,对于 “ll”'l'.

我想要的是找到我的字符串的所有变体,给定这个规则字典。例如,使用上面的两个规则和字符串 'hello',我想返回:

['hello', 'ello', 'helo', 'elo']

感谢任何帮助,谢谢!

最佳答案

编写一个接受输入的子字符串的递归函数。然后此函数检查所有规则。对于每个匹配的规则,进行一次替换,并通过递归调用处理字符串的其余部分:

def apply_rules(rules, input, start=0):
# First yield the outcome of no applied rules.
yield input[start:]

for match, replace in rules:
# Find the first match for this rule.
index = input.find(match, start)
if index < 0:
# No match -- skip to next one
continue
# Prepare the result of the replacement.
prefix = input[start:index] + replace
# Apply further rules to the rest of the string
# by a recursive call.
for suffix in apply_rules(rules, input, index + len(match)):
yield prefix + suffix

像这样使用它:

>>> rules = [('he','e'), ('ll','l'), ('e','ee')]
>>> list(apply_rules(rules, 'hello'))
['hello', 'ello', 'elo', 'helo', 'heello', 'heelo']

请注意,我不允许将规则应用于替换的字符串,以防止无限结果的情况,如对此问题的评论中所示。

关于python - 弦乐变奏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30153837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com