If not, then a canonical name for a function? 'Cycle' makes sense to me, but that's taken.
The example in the header is written for clarity and brevity. Real cases I'm working with have a lot of repetition. (e.g., I want [1, 1, 0, 0, 0, 2, 1] to "match" [0, 0, 2, 1, 1, 1, 0])
This type of thing is obscuring my algorithm and filling my code with otherwise useless repetition.
You can get the cycles of the list with:
def cycles(a):
return [ a[i:] + a[:i] for i in range(len(a)) ]
You can then check if b is a cycle of a with:
b in cycles(a)
If the length of the list is long, or if want to make multiple comparison to the same cycles, it may be beneficial (performance wise) to embed the results in a set.
set_cycles = set(cycles(a))
b in set_cycles
You can prevent necessarily constructing all the cycles by embedding the equality check in the list and using any:
any( b == a[i:]+a[:i] for i in range(len(a)))
You could also achieve this effect by turning the cycles
function into a generator.
Misunderstood your question earlier. If you want to check if any cycle of a list l1
matches a list l2
the best (cleanest/most pythonic) method is probably any(l1 == l2[i:] + l2[:i] for i in xrange(len(l2)))
. There is also a rotate
method in collections.deque
that you might find useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With