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?
No, listobjects do not have standard methods of "related differences" or the like. However, using the function pairwiseindicated in the itertoolsrecipes :
list
pairwise
itertools
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
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
:
>>> s = [1, 3, 5, 9, 15, 30] >>> max(x[0] - x[1] for x in zip(s[1:], s)) 15
max zip, .
max
zip
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))
. , , :
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
reduce(), , , :
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() .
abs()