How to get maximum distance (step) between values ​​in python?

Given that a list of integers exists, does the default method find the maximum distance between values?

So, if I have this array

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

The maximum step between the values ​​is 15. Does the list object have a method for this?

+4
source share
6 answers

No, listobjects do not have standard methods of "related differences" or the like. However, using the function pairwiseindicated in the itertoolsrecipes :

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

... you can (briefly and effectively) define

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

No, but this is trivial for the code:

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

:

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

max zip, .

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

"15".

"numpy", :

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

. , , :

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

, :

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
0

reduce(), , , :

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]

, .

[10,20,30,5]? 10 25? 25, abs() .

0

All Articles