我試圖找出將第一個字符串s1更改爲所需的更改次數。我寫了一個函數來做到這一點 ,但到目前爲止,我的問題是,如果前兩個字符 不同,那麼它會返回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
這個名字是[編輯距離](https://en.wikipedia.org/wiki/Edit_distance) – Cuadue