2013-12-11 4 views

답변

2

재귀 당신은 함수가 적용되는 것을 알고 :

  • 기본 경우) 빈 문자열, 빈 문자열을 반환해야합니다;
  • 사례) b으로 시작하는 문자열은 ba으로 대체하고 나머지 문자열을 확인해야합니다.

    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") 
    

  • REC 경우) 그렇지, 문자열의 나머지 부분에 체인 된 문자열의 첫 번째 문자가 반복적으로 여기

반환 된 알고리즘 반환 출력 :

ok this is ok a simple ok test 
관련 문제