I'm looking for an efficient way to compare lists of numbers to see if they match at any rotation (comparing 2 circular lists).
When the lists don't have duplicates, picking smallest/largest value and rotating both lists before comparisons works. But when there may be many duplicate large values, this isn't so simple.
For example, lists [9, 2, 0, 0, 9]
and [0, 0, 9, 9, 2]
are matches,
where [9, 0, 2, 0, 9]
won't (since the order is different).
Heres an example of an in-efficient function which works.
def min_list_rotation(ls):
return min((ls[i:] + ls[:i] for i in range(len(ls))))
# example use
ls_a = [9, 2, 0, 0, 9]
ls_b = [0, 0, 9, 9, 2]
print(min_list_rotation(ls_a) == min_list_rotation(ls_b))
This can be improved on for efficiency...
- check sorted lists match before running exhaustive tests.
- only test rotations that start with the minimum value
(skipping matching values after that)
effectively finding the minimum value with the furthest & smallest number after it (continually - in the case there are multiple matching next-biggest values). - compare rotations without creating the new lists each time..
However its still not a very efficient method since it relies on checking many possibilities.
Is there a more efficient way to perform this comparison?
Related question: Compare rotated lists in python