Reputation: 191
Suppose we have v1 = list("abcdabcd")
and v2 = list("caabccab")
, where a
corresponds to c
, and b
corresponds to d
. Note that the list()
has separated strings into a list of singletons.
How can we use recursion to find out the longest pair(s), where a pair means, for example, that cda
and abc
in this case.
Upvotes: 0
Views: 387
Reputation: 9575
You can iterate through and detect matches:
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')
Upvotes: 1