1
문자열과 하위 문자열 두 개 (이름이 a 및 b) 인 경우 b의 모든 항목을 a로 대체하고 새 문자열을 반환하는 재귀 함수를 작성해야합니다. .재귀를 사용하여 하위 문자열의 모든 항목을 다른 하위 문자열로 바꿉니다.
누군가 어떻게 도와 줄 수 있습니까?
문자열과 하위 문자열 두 개 (이름이 a 및 b) 인 경우 b의 모든 항목을 a로 대체하고 새 문자열을 반환하는 재귀 함수를 작성해야합니다. .재귀를 사용하여 하위 문자열의 모든 항목을 다른 하위 문자열로 바꿉니다.
누군가 어떻게 도와 줄 수 있습니까?
재귀 당신은 함수가 적용되는 것을 알고 :
b
으로 시작하는 문자열은 b
을 a
으로 대체하고 나머지 문자열을 확인해야합니다. 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
어떤 의미에서 재귀? –
코드를 알려주십시오. –