Finding the largest delta between two integers in a list

This is more as an advertisement for the brilliant recipes in the Python itertools help.

In this case use pairwise as shown in the help linked above.

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

values = [55, 55, 56, 57, 57, 57, 57, 62, 63, 64, 79, 80]

print max(b - a for a,b in pairwise(values))

Try timing some of these with the timeit module:

>>> values = [55, 55, 56, 57, 57, 57, 57, 62, 63, 64, 79, 80]
>>> max(values[i+1] - values[i] for i in xrange(0, len(values) - 1))
15
>>> max(v1 - v0 for v0, v1 in zip(values[:-1], values[1:]))
15
>>> from itertools import izip, islice
>>> max(v1 - v0 for v0, v1 in izip(values[:-1], values[1:]))
15
>>> max(v1 - v0 for v0, v1 in izip(values, islice(values,1,None)))
15
>>>

max(abs(x - y) for (x, y) in zip(values[1:], values[:-1]))

Tags:

Python

List