2013-12-11 27 views

回答

2

递归你知道你的函数适用于:

  • 基本情况)一个空字符串,必须返回一个空字符串;
  • rec case)以b开头的字符串必须用a替换b并检查字符串的其余部分;
  • REC情况下)否则,返回链接到该字符串的其余部分字符串的第一个字符返回递归

这里的算法:

def rec_replace(string, a, b): 
    if not string: #if the string is empty 
     return "" 
    elif string[:len(b)] == b: #if the string start with b, replace it with a 
     return a + rec_replace(string[len(b):], a, b) 
    else: #else, add this character and go to the next one 
     return string[0] + rec_replace(string[1:], a, b) 

测试:

print rec_replace("hello this is hello a simple hello test", "ok", "hello") 

输出:

ok this is ok a simple ok test 
相关问题