Daniel Cohen
Daniel Cohen

Reputation: 301

Compare Sequences Python

Is there a way in python to compare 2 sequences in lists even if they are not normalized (i think this is the right word). For example:

a = [1,1,2,3,3,1,5]
b = [2,3,3,1,5,1,1]
c = [1,1,1,2,3,3,5]

a == b should return True as they contain the same sequence just from a different starting point.

c == a should return False as although they contain the same elements, they do not contain the same sequence

The only thing I can thing of is rather inelegant. I would compare 2 lists and if they are not equal, shift the last element of the list to the front and compare again. Repeat this until I have shifted the entire list once. However, I will be working with some very large lists so this will be very inefficient

Upvotes: 1

Views: 496

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

This might be more efficient than shifting elements:

>>> a = [1, 1, 2, 3, 3, 1, 5]
>>> b = [2, 3, 3, 1, 5, 1, 1]
>>> c = [1, 1, 1, 2, 3, 3, 5]
>>> astr, bstr, cstr = ["".join(map(str, x)) for x in (a, b, c)]
>>> astr in bstr*2
True
>>> cstr in astr*2
False

What it does is basically join the lists to strings and check if the first string is contained in the other 'doubled'.
Using strings is probably the fastest and should work for simple cases like in the OP. As a more general approach, you can apply the same idea to list slices, e.g.:

>>> any(idx for idx in range(len(a)) if (b*2)[idx:idx+len(a)] == a)
True

Upvotes: 1

Related Questions