递归查找两个文本之间的差异



我正在尝试构建一个递归函数,该函数可以识别两个字符串之间的不同字符

str1 = "https://google.com"
str2 = "https://goSiogllveer.com"
#expected output = "Silver"

示例2

str1 = 'http://www.wood.com/'
str2 = "http://www.waoBcod.com/"
#expected_output = "aBc"

理想情况下,我正在寻找递归解决方案,但任何其他方法都是可以接受的

试试这个,不管str1中有什么,都从str2 中删除

str1, str2 = list(str1), list(str2)
[str2.remove(i) for i in str1 if i in str2]
print("".join(str2))

这可能不是最优雅的解决方案,也不是递归的,但它是:

str1 = 'http://www.wood.com/'
str2 = "http://www.waoBcod.com/"
list1 = list(str1)
list2 = list(str2)
count = 0
diff = []
for c in list2:
if c == list1[count]:
count += 1
else:
diff.append(c)
diff = "".join(diff)
print(diff)

您可以尝试:

>>> from collections import Counter
>>> str1 = "https://google.com"
>>> str2 = "https://goSiogllveer.com"
>>> list((Counter(list(str2)) - Counter(list(str1))).elements())
['S', 'i', 'l', 'v', 'e', 'r']
>>> "".join(list((Counter(list(str2)) - Counter(list(str1))).elements()))
'Silver'

编辑

>>> Counter(list(str1))
Counter({'o': 3, 't': 2, '/': 2, 'g': 2, 'h': 1, 'p': 1, 's': 1, ':': 1, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1})
>>> Counter(list(str2))
Counter({'o': 3, 't': 2, '/': 2, 'g': 2, 'l': 2, 'e': 2, 'h': 1, 'p': 1, 's': 1, ':': 1, 'S': 1, 'i': 1, 'v': 1, 'r': 1, '.': 1, 'c': 1, 'm': 1})

这不是递归解决方案,因为这不是真正必要的:

str1 = "https://google.com"
str2 = "https://goSiogllveer.com"
s1, s2 = (str1, str2) if len(str1) > len(str2) else (str2, str1)
j = 0
s = ''
for i in range(len(s1)):
if s1[i] != s2[j]:
s += s1[i]
else:
if (j := j + 1) >= len(s2):
break
print(s)

输出:

Silver

最新更新