-->

字符串的变化(String Variations)

2019-10-23 01:28发布

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

这些规则将意味着任何发生``“他”在我的字符串可以用替代'e' ,同样为'll''l'

我想要的是找到我的字符串的所有变化,因为这本词典的规则。 例如,从上述两个规则和字符串'hello' ,我想回:

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

任何帮助表示赞赏,谢谢!

Answer 1:

写一个递归函数,是以输入的字符串。 然后,该函数将检查所有规则。 对于每个匹配的规则,一个替换完成,而字符串的其余部分由递归调用处理:

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

请注意,我不允许替换字符串应用规则,以防止无限的结果案件在评论这个问题证明。



文章来源: String Variations