Reputation: 11
In python, need to define a function that takes 2 lists. If the last part of the first list is same as first part of the second list, then delete the same part and added rest 2 lists together. such as:
I have defined a helper function called prefix that takes 2 lists and return true if the first list is prefix of the second list. Otherwise return false.
Upvotes: 0
Views: 89
Reputation: 25548
You could try:
def merge(seq1, seq2):
n1 = len(seq1)
for i in range(n1):
if seq1[i:] == seq2[:n1-i]:
return seq1 + seq2[n1-i:]
return seq1 + seq2
In [52]: merge(['a','a','a'],['g','g','g'])
Out[52]: ['a', 'a', 'a', 'g', 'g', 'g']
In [53]: merge(['a','t','t','a'],['t','t','a','a'])
Out[53]: ['a', 't', 't', 'a', 'a']
In [54]: merge(['a','t','t','a'],['t','t','a','a'])
Out[54]: ['a', 't', 't', 'a', 'a']
In [55]: merge(['a', 'a', 'a', 't', 't', 't', 't'], ['t', 't', 't', 't', 'g', 'g', 'g', 'g'])
Out[55]: ['a', 'a', 'a', 't', 't', 't', 't', 'g', 'g', 'g', 'g']
It doesn't modify the original lists, but you could do this easily if you need to. (This isn't the way to go if your lists are very long with short overlaps because it checks from the beginning of the first.)
Upvotes: 1
Reputation: 1940
def merge(L1, L2):
middle = []
while L1 and L2 and L1[-1] == L2[0]:
middle.append(L2[0])
L1 = L1[:-2]
L2 = L2[1:]
return L1 + middle + L2
Upvotes: 0