Say I have a list v = [1, 2, 3, 4, 3, 1, 2]
. I want to write a function, find_pair
which will check if two numbers are in the list and adjacent to each other. So, find_pair(v, 2, 3)
should return True
, but find_pair(v, 1, 4)
should return False
.
Is it possible to implement find_pair
without a loop?
If you are looking for a function that returns True or False depending on whether the two elements are consecutive or not irrespective of their orders then use this:
But if the order of the elements are important then remove the abs() function inside the if condition. UPDATE:
A more robust one could be(if y is expected to follow x):
You're going to need a loop.
Unlike Python strings which support a subsequence test using the in operator, Python lists do not have a builtin subsequence test.
Combining a few ideas here, these both seem to do the trick and are very fast
The simpler InList version is only slightly slower than @abhijit's solution while doing one less test, but still almost twice as fast as the top solution. The FasterInList version is about 25% faster than InList.
I know you are already happy with one of the answer's in this post but, you may try with the following
Ok Curiosity got better of me and so wanted to test how does this implementation performed with the fastest posted implementation
Gosh this is way fast
Note** Thanks Michael for pointing it out. I have corrected it and here is my updated solution.
Perhaps even simpler:
This is probably a bit of a round about way to do it, but you could use (with your variable v above):