我正在试图找出改变所需的更改次数 第一个字符串,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
答案 0 :(得分:2)
您忽略了递归调用的返回值。它们返回一个长度,但这些值被丢弃在地板上。如果我们删除这些递归调用,那么,您的代码等同于:
length = 0
if s1[0] == s2[0]:
pass
else:
length += 1
return length
如您所见,它只会返回0或1。
您需要获取递归值,然后在第一个字符匹配时有条件地添加1。
if s1[0] == s2[0]:
return num_of_changes(s1[length+1:], s2[length+1:])
else:
return num_of_changes(s1[length+1:], s2[length+1:]) + 1
通过将length+1
更改为1
并合并两个return语句,可以将其简化为:
return num_of_changes(s1[1:], s2[1:]) + (1 if s1[0] == s2[0] else 0)
它可能有点密集,但这使得你很清楚你要返回的是什么:它是递归调用的值,加上s1[0] == s2[0]
时的值。
答案 1 :(得分:2)
您要查找的功能称为两个字符串之间的编辑距离或Levenshtein距离。您可以在python-Levenshtein包中找到它。通过以下方式安装:
$ sudo pip install python-Levenshtein
并像这样使用它:
>>> import Levenshtein
>>> Levenshtein.distance('abba', 'baba')
2