递归比较两个列表

时间:2019-04-22 02:42:07

标签: python python-3.x

假设我们有v1 = list("abcdabcd")v2 = list("caabccab"),其中a对应于c,而b对应于d。请注意,list()已将字符串分成单例列表。

我们如何使用递归来找出最长的一对,例如,在这种情况下,一对意味着cdaabc

1 个答案:

答案 0 :(得分:1)

您可以遍历并检测匹配项:

v1 = list("abcdabcd")
v2 = list("caabccab")

def longest_match(v1, v2):
    consecutive, max_c, max_m1, max_m2 = [0]*4
    match1, match2 = '', ''
    a, b, c, d = 'a', 'b', 'c', 'd'
    for i in range(len(v1)):
        if (v1[i] == a and v2[i] == c) or (v1[i] == c and v2[i] == a) or (v1[i] == b and v2[i] == d) or (v1[i] == d and v2[i] == b):
            consecutive += 1
            match1 += v1[i]
            match2 += v2[i]
        else:
            if consecutive > max_c:
                max_c = consecutive
                max_m1, max_m2 = match1, match2
            consecutive, match1, match2 = 0, '', ''

    match = (max_m1, max_m2)

    return max_c, match

print(longest_match(v1, v2)[1])  # ('cda', 'abc')