【问题标题】:String Variations弦乐变奏曲
【发布时间】:2015-05-10 16:33:01
【问题描述】:

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

这些规则意味着我的字符串中任何出现的“'he'都可以替换为'e''ll''l'也是如此。

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

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

感谢任何帮助,谢谢!

【问题讨论】:

  • 使用规则 e=>ee 查找所有结果
  • @StefanPochmann 如果这是唯一的规则,我希望 ['hello', 'heello']。使用所有三个规则,它将是 ['hello', 'ello', 'helo', 'elo', 'heello', 'eello', 'heelo', 'eelo']。
  • @Clayton @StefanPochmann 有一点:如果您允许将规则应用于规则的结果,例如您的示例中的hello -> ello -> eello,则必须考虑无限循环。在您的评论中,您隐含地假定您不能将规则 e -> ee 应用到多个,否则您最终会得到无限的结果:hello, heello, heeello, heeeello, ...。可以使用多个规则构造一个类似的示例:e -> ef, f -> e

标签: python string combinations variations


【解决方案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']

请注意,我不允许将规则应用于替换的字符串,以防止出现无限结果的情况,如该问题的 cmets 所示。

【讨论】:

  • 您可能希望将第一个 for 修改为 for match, replace in rules.items()
  • 谢谢,太好了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 2019-05-17
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多