You don't need the function _matching_lists
, as you can just use ==
:
>>> [1,2,3] == [1,2,3]
True
>>> [1,2,3] == [3,1,2]
False
I suggest using any()
to return as soon a match is found, and using a generator expression to avoid constructing a list of rotations in memory:
def _compare_rotated_lists(a, b):
"""Return `True` if the list `a` is equal to a rotation of the list `b`."""
return any(a == b[i:] + b[:i] for i in range(len(b)))
You might consider checking that the lists are the same length, to reject the easy case quickly.
return len(a) == len(b) and any(a == b[i:] + b[:i] for i in range(len(b)))
As discussed in comments, if you know that the elements of a
and b
are hashable, you can do the initial comparison using collections.Counter
:
return Counter(a) == Counter(b) and any(a == b[i:] + b[:i] for i in range(len(b)))
and if you know that the elements of a
and b
are comparable, you can do the initial comparison using sorted
:
return sorted(a) == sorted(b) and any(a == b[i:] + b[:i] for i in range(len(b)))