Combining several ideas here, they both seem to be doing their job very quickly.
def InList(v, (x, y)):
return any((x == v[i] and y == v[i + 1]) for i in xrange(len(v) - 1))
def FasterInList(v, (x, y)):
if x in v:
indices = [i for i, match in enumerate(v) if match == x]
for i in indices:
if v[i+1] == y:
return True
return False
The simpler version of InList is only slightly slower than the @abhijit solution, but it performs one test less, but still almost twice as fast as the top solution. The FasterInList version is about 25% faster than InList.
import timeit
abhijit = """
v = [1,2,3,4,3,1,2]
def abhijit(v,(i,j)):
start=1
try:
while True:
if v[v.index(i,start)+1]==j and v[v.index(j,start)-1]==i:
return True
start=v.index(i)+1
except IndexError:
return False
except ValueError:
return False
abhijit(v,(2,3))
abhijit(v,(4,5))
abhijit(v,(1,2))
abhijit(v,(12,2))
"""
# abhijit(v,(3,2)) this never breaks out of the while loop
top = """
v = [1,2,3,4,3,1,2]
def top(v,(x,y)):
any([x,y] == v[i:i+2] for i in xrange(len(v) - 1))
top(v,(2,3))
top(v,(4,5))
top(v,(1,2))
top(v,(12,2))
top(v,(3,2))
"""
InList = """
v = [1,2,3,4,3,1,2]
def InList(v, (x, y)):
return any((x == v[i] and y == v[i + 1]) for i in xrange(len(v) - 1))
InList(v,(2,3))
InList(v,(4,5))
InList(v,(1,2))
InList(v,(12,2))
InList(v,(3,2))
"""
FasterInList = """
v = [1,2,3,4,3,1,2]
def FasterInList(v, (x, y)):
if x in v:
indices = [i for i, match in enumerate(v) if match == x]
for i in indices:
if v[i + 1] == y:
return True
return False
FasterInList(v,(2,3))
FasterInList(v,(4,5))
FasterInList(v,(1,2))
FasterInList(v,(12,2))
FasterInList(v,(3,2))
"""
top_timer = timeit.Timer(stmt=top)
abhijit_timer = timeit.Timer(stmt=abhijit)
InList_timer = timeit.Timer(stmt=InList)
FasterInList_timer = timeit.Timer(stmt=FasterInList)
print "%.2f usec/pass" % (1000000 * top_timer.timeit(number=100000)/100000) # 8.79 usec/pass
print "%.2f usec/pass" % (1000000 * abhijit_timer.timeit(number=100000)/100000) # 4.42 usec/pass
print "%.2f usec/pass" % (1000000 * InList_timer.timeit(number=100000)/100000) # 4.66 usec/pass
print "%.2f usec/pass" % (1000000 * FasterInList_timer.timeit(number=100000)/100000) # 3.70 usec/pass