Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pairwise traversal of a list or tuple

Tags:

a = [5, 66, 7, 8, 9, ...] 

Is it possible to make an iteration instead of writing like this?

a[1] - a[0]  a[2] - a[1]  a[3] - a[2]  a[4] - a[3] 

...

Thank you!

like image 497
Bob Avatar asked Oct 03 '10 11:10

Bob


1 Answers

It's ok to use range. However, programming (like maths) is about building on abstractions. Consecutive pairs [(x0, x1), (x1, x2), ..., (xn-2, xn-1)], are called pairwise combinations. See an example in the itertools docs. Once you have this function in your toolset, you can write:

for x, y in pairwise(xs):     print(y - x) 

Or used as a generator expression:

consecutive_diffs = (y - x for (x, y) in pairwise(xs)) 
like image 140
tokland Avatar answered Oct 12 '22 12:10

tokland