Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to determine if two given numbers are adjacent in integer sequence

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.

like image 665
fiacre Avatar asked Aug 14 '26 23:08

fiacre


1 Answers

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
>>> 
like image 114
Prune Avatar answered Aug 16 '26 13:08

Prune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!