Usi Usi
Usi Usi

Reputation: 2997

Method to get the max distance (step) between values in python?

Given an list of integers does exists a default method find the max distance between values?

So if I have this array

[1, 3, 5, 9, 15, 30]

The max step between the values is 15. Does the list object has a method for do that?

Upvotes: 4

Views: 2175

Answers (6)

Martin Evans
Martin Evans

Reputation: 46779

It is possible to use the reduce() function, but it is not that elegant as you need some way to keep track of the previous value:

def step(maxStep, cur):
    if isinstance(maxStep, int):
        maxStep = (abs(maxStep-cur), cur)

    return (max(maxStep[0], abs(maxStep[1]-cur)), cur)

l = [1, 3, 5, 9, 15, 30]

print reduce(step, l)[0]

The solution works by returing the previous value and the accumulated max calculation as a tuple for each iteration.

Also what is the expected outcome for [10,20,30,5]? Is it 10 or 25? If 25 then you need to add abs() to your calculation.

Upvotes: 0

Frerich Raabe
Frerich Raabe

Reputation: 94439

No, list objects have no standard "adjacent differences" method or the like. However, using the pairwise function mentioned in the itertools recipes:

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

...you can (concisely and efficiently) define

>>> max(b-a for (a,b) in pairwise([1, 3, 5, 9, 15, 30]))
15

Upvotes: 8

DevShark
DevShark

Reputation: 9122

The list object does not. However, it is pretty quick to write a function that does that:

def max_step(my_list):
    max_step = 0
    for ind in xrange(len(my_list)-1):
        step = my_list[ind+1] - my_list[ind]
        if step > max_step:
            max_step = step
    return max_step

>>> max_step([1, 3, 5, 9, 15, 30])
15

Or if you prefer even shorter:

max_step = lambda l: max([l[i+1] - l[i] for i in xrange(len(l)-1)])
>>> max_step([1, 3, 5, 9, 15, 30])
15

Upvotes: 0

Cleb
Cleb

Reputation: 26027

l=[1, 3, 5, 9, 15, 30]
max([j-i for i, j in zip(l[:-1], l[1:])]) 

That is using pure python and gives you the desired output "15".

If you like to work with "numpy" you could do:

import numpy as np
max(np.diff(l))

Upvotes: 2

Simeon Visser
Simeon Visser

Reputation: 122486

You can do:

>>> s = [1, 3, 5, 9, 15, 30]
>>> max(x[0] - x[1] for x in zip(s[1:], s))
15

This uses max and zip. It computes the difference between all consecutive elements and returns the max of those.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599876

No, but it's trivial to code:

last = data[0]
dist = 0
for i in data[1:]:
    dist = max(dist, i-last)
    last = i
return dist

Upvotes: 2

Related Questions