-1
def make_converter(match, replacement):        
    d={match : replacement}         
    return d

def apply_converter(converter, string):    
    c1= "".join(str(x) for x in converter.keys())
    c2= "".join(str(x) for x in converter.values())
    print c1,c2
    c3=string.find(c1)
    if c3==-1:
        return string
    string=string.replace(c1,c2,1)
    apply_converter(converter,string)

# For example,

c1 = make_converter('aa', 'a')
print apply_converter(c1, 'aaaa')
#>>> a

c = make_converter('aba', 'b')
print apply_converter(c, 'aaaaaabaaaaa')
#>>> ab
4

2 回答 2

1

您没有返回递归的结果。string如果未找到匹配项,您的函数将返回输入,否则将不返回任何内容!

你要:

return apply_converter(converter, string)
于 2013-01-26T10:21:03.713 回答
0

除了不返回结果外,我还进行了一些其他清理:

def make_converter(match, replacement):        
    return (match, replacement)

def apply_converter(converter, string):    
    old, new = converter
    replaced = string.replace(old, new, 1)
    while replaced != string:
        string = replaced
        replaced = string.replace(old, new, 1)
    return string
于 2013-01-26T10:25:15.943 回答