Lucas Reno
Lucas Reno

Reputation: 153

Finding the largest delta between two integers in a list

I have a list of integers, i.e.:

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

I am trying to find the largest difference between two consecutive numbers.

In this case it would be 15 from 64->79.

The numbers can be negative or positive, increasing or decreasing or both. The important thing is I need to find the largest delta between two consecutive numbers.

What is the fastest way to do this? These lists can contain anywhere from hundreds to thousands of integers.

This is the code I have right now:

prev_value = values[0]
largest_delta = 0

for value in values:
  delta = value - prev_value
  if delta > largest_delta:
    largest_delta = delta
  prev_value = value

  return largest_delta

Is there a faster way to do this? It takes a while.

Upvotes: 15

Views: 7578

Answers (5)

Xavier Guihot
Xavier Guihot

Reputation: 61726

Starting in Python 3.10, the new pairwise function provides a way to slide through pairs of consecutive elements, and thus find each of their differences:

from itertools import pairwise

# values = [55, 55, 56, 57, 57, 57, 57, 62, 63, 64, 79, 80]
max(abs(x-y) for x, y in pairwise(values))
# 15

The intermediate result of pairwise:

pairwise([55, 55, 56, 57, 57, 57, 57, 62, 63, 64, 79, 80])
# [(55, 55), (55, 56), (56, 57), (57, 57), (57, 57), (57, 57), ...]

Upvotes: 1

hugo24
hugo24

Reputation: 1108

With reduce (ugly i guess)

>>> foo = [5, 5, 5, 5, 8, 8, 9]    
>>> print reduce(lambda x, y: (max(x[0], y - x[1]), y), foo, (0, foo[0]))[0]
3

Upvotes: 2

Muhammad Alkarouri
Muhammad Alkarouri

Reputation: 24672

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))

Upvotes: 2

John Machin
John Machin

Reputation: 83002

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
>>>

Upvotes: 2

dan04
dan04

Reputation: 91209

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

Upvotes: 25

Related Questions