Given integers a, b such that a < b; and some ordered iterable sequence of integers, seq. Determine whether a and b appear adjacent, in that order, anywhere in seq
The obvious first pass is :
assume a < b (if a > b, just switch values).
>>> idx = 0
>>> for i in range(0, len(l)):
... if a == l[i]:
... idx = i
...
>>> b == l[idx+1]
This feels clumsy.
For example, given
>>> [1, 2, 3, 8]
If a is 1 and b is 3, they are not adjacent, if a is 3 in b is 8, they are.
Something tells me there is a more pythonic way of doing this or that this is a well explored problem, and I am missing a clearer/cleaner way to approach it.
Use the any reducer to determine whether any adjacent pair matches (a,b):
>>> seq = [1, 2, 3, 8]
>>> a = 3
>>> b = 8
>>> any((seq[i], seq[i+1]) == (a,b) for i in range(len(seq)-1))
True
>>> b = 1
>>> any((seq[i], seq[i+1]) == (a,b) for i in range(len(seq)-1))
False
>>>
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