Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clean way to accomplish -- if x in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]:?

Tags:

python

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.

like image 691
Shay Avatar asked Dec 12 '22 20:12

Shay


2 Answers

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.

like image 65
cmh Avatar answered Dec 26 '22 19:12

cmh


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.

like image 39
arshajii Avatar answered Dec 26 '22 19:12

arshajii