A clean way to do it is if x is in [(0, 1, 2), (2, 0, 1), (1, 2, 0)] :?

If not, then the canonical name for the function? "Cycle" makes sense to me, but that's taken.

The example in the title is written for clarity and conciseness. In real cases, with which I work, there are many repetitions. (for example, I want [1, 1, 0, 0, 0, 0, 2, 1] to match [0, 0, 2, 1, 1, 1, 0])

This type of thing hides my algorithm and fills my code with otherwise useless repetition.

+4
source share
3 answers

You can get list loops with:

def cycles(a): return [ a[i:] + a[:i] for i in range(len(a)) ] 

Then you can check if b is a loop with:

 b in cycles(a) 

If the length of the list is long or if you want to make several comparisons with the same loops, it may be useful (in terms of performance) to embed the results in a set.

 set_cycles = set(cycles(a)) b in set_cycles 

You can prevent the need to build all loops by inserting an equality check into the list and using any:

 any( b == a[i:]+a[:i] for i in range(len(a))) 

You can also achieve this effect by turning the cycles function into a generator.

+8
source

Did not understand your question before. If you want to check if any cycle of the list l1 list l2 best (cleanest / most pythonic) method, 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.

+5
source

You can use cycle from itertools along with islice to crop it. This basically puts this answer in a list comprehension, so the list is shifted once for each item.

 >>> from itertools import islice, cycle >>> l = [0,1,2] >>> [tuple(islice(cycle(t),i,i+len(t))) for i,_ in enumerate(l)] [(0, 1, 2), (1, 2, 0), (2, 0, 1)] 
0
source

Source: https://habr.com/ru/post/1447535/


All Articles