2013-12-11 42 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 
相關問題