문자열을 s1에서 s2로 변경하는 데 필요한 변경 횟수를 알아 내려고합니다. 내가 정확히 할 함수를 썼다지만 내가 처음으로 두 문자 다를 경우 그것은 1을 반환하고 문자열의 나머지 부분을 보지 않는다면 내가 지금까지 가지고있는 문제가 있습니다.문자열을 다른 것으로 바꾸는 데 걸리는 변경 횟수
는 여기에 지금까지이 작업은 다음과 같습니다
def num_of_changes(s1, s2):
if not s1:
return len(s2)
if not s2:
return len(s1)
length = 0
# if the first char in both the string are the same, then call the function
# again on the rest of the string after the first char.
# so if s1 = cat and s2 = cbt since the first char on both strings is
# the same it call the function again on the rest, the rest in this case
# being s1 = at and s2 = bt
if s1[0] == s2[0]:
num_of_changes(s1[length+1:], s2[length+1:])
# if the first characters on both the strings aren't the same, then
# increase the length by 1, and call the function again on the rest of the
# string after length + 1.
# so if s1 = cat and s2 = bat, since the first char from both the strings
# arent the same it calls the function on length+1. Since the length
# increased to 1 becase the first char isn't the same, the it would be
# length=1, so 1+1
# Therefore, it would call the function on s1 = at and s2 = at
else:
length += 1
num_of_changes(s1[length+1:], s2[length+1:])
# returns the number stored in the length variable.
return length
재귀 함수는 PARAM로 길이를 데리고있다, 그래서 당신은 모든 재귀 호출에 전달할 수 있습니다. – gtgaxiola
이 이름은 [edit distance] (https://en.wikipedia.org/wiki/Edit_distance) – Cuadue