Alright, so I have two lists, as such:
[1, 2, 3, 4, 5]
, [4, 5, 6, 7]
.
You can try the following:
>>> a = [1, 3, 9, 8, 3, 4, 5]
>>> b = [3, 4, 5, 7, 8]
>>> matches = (i for i in xrange(len(b), 0, -1) if b[:i] == a[-i:])
>>> i = next(matches, 0)
>>> a + b[i:]
[1, 3, 9, 8, 3, 4, 5, 7, 8]
The idea is we check the first i
elements of b
(b[:i]
) with the last i
elements of a
(a[-i:]
). We take i
in decreasing order, starting from the length of b
until 1 (xrange(len(b), 0, -1)
) because we want to match as much as possible. We take the first such i
by using next
and if we don't find it we use the zero value (next(..., 0)
). From the moment we found the i
, we add to a
the elements of b
from index i
.