Python 3 - A Specific Operation on a List -


i have list of length n having positive numbers like:

list = [a,b,c,d,g,h,w,x,y,z] 

where a,b,c... numbers. want check if list has any 2 consecutive pairs of numbers satisfy below criteria:

[w,x] , [y,z] such w = z +/- 1 , x = y +/- 1 , abs(w-x) == abs(y-z) 

for example -

>>> l [0, 3, 2, 5, 4, 1, 6] (2,5) , (4,1) such consecutive pairs of list elements. 

any tips useful.

you can play zip function :

>>> z=list(zip(l[0::2],l[1::2])) >>> new=zip(z,z[1:]) >>> [([w,x],[y,z]) [w,x],[y,z] in new if abs(w-z)==1 , abs(x-y)== 1 , abs(w-x) == abs(y-z)] [([2, 5], [4, 1])] 

note long lists can use itertools.izip instead of zip.

another example :

>>> l=[0, 3, 2, 5, 4, 1] >>> z=zip(l[0::2],l[1::2]) >>> new=zip(z,z[1:]) >>> [([w,x],[y,z]) [w,x],[y,z] in new if abs(w-z)==1 , abs(x-y)== 1 , abs(w-x) == abs(y-z)] [([2, 5], [4, 1])] 

based on comments notes cases more complete way can :

>>> l=[8, 0, 3, 2, 5, 4, 1, 6] >>> z1=zip(l[0::2],l[1::2]) >>> new1=zip(z1,z1[1:])  >>> z2=zip(l[1::2],l[2::2]) >>> new2=zip(z2,z2[1:])  >>> total=new1+new2 >>> [([w,x],[y,z]) [w,x],[y,z] in total if abs(w-z)==1 , abs(x-y)== 1 , abs(w-x) == abs(y-z)] [([2, 5], [4, 1])] 

Comments