Python 弦乐变奏

Python 弦乐变奏,python,string,combinations,variations,Python,String,Combinations,Variations,我有一个python中的字符串和一个“规则”字典,或者可能对字符串进行修改。例如,一条规则的键可能为'he'且值可能为'e',或者键可能为'll'且值可能为'l' 这些规则意味着在我的字符串中出现的任何“he”都可以替换为'e',类似地,对于'll'和'l' 我想要的是找到我的字符串的所有变体,给定这个规则字典。例如,使用上面的两条规则和字符串'hello',我想返回: ['hello', 'ello', 'helo', 'elo'] 感谢您的帮助,谢谢 编写一个接收输入子字符串的递归函数。然

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

这些规则意味着在我的字符串中出现的任何“he”都可以替换为
'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

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

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

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

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

使用规则e查找所有结果=>ee@StefanPochmann如果这是唯一的规则,我会期待['hello','heello']。在这三条规则中,“你好”、“ELO”、“ELO”、“Hello”、“Eello”、“Heelo”、“Eelo”等都有一点:如果你允许规则应用到规则的结果上,例如“代码> Hello—> E略-> Eello”/代码>,在你的例子中,你必须考虑无限循环。在您的评论中,您隐含地假设您不能应用规则
e->ee
不止一个,否则您将得到无限的结果:
你好,heello,heello,heeeello,…
。类似的示例可以用多个规则构造:
e->ef,f->e
。使用规则e=>ee@StefanPochmann如果这是唯一的规则,我会期待['hello','heello']。在这三条规则中,“你好”、“ELO”、“ELO”、“Hello”、“Eello”、“Heelo”、“Eelo”等都有一点:如果你允许规则应用到规则的结果上,例如“代码> Hello—> E略-> Eello”/代码>,在你的例子中,你必须考虑无限循环。在您的评论中,您隐含地假设您不能应用规则
e->ee
不止一个,否则您将得到无限的结果:
你好,heello,heello,heeeello,…
。类似的示例可以用多个规则构造:
e->ef,f->e
。您可能希望将第一个
修改为
,以便在规则中进行匹配,替换。items()
@Pynchia My
apply_rules
碰巧需要一个成对的序列来表示规则,我把它留给读者去适应不同的表达方式,比如字典。谢谢,这太棒了!您可能希望将第一个
修改为
,以
匹配,在规则中替换。items()
@Pynchia My
apply_rules
碰巧需要一系列对来表示规则,我让读者自行调整以适应不同的表示,例如字典。谢谢,这太棒了!