min max of a list
Steven Bethard
steven.bethard at gmail.com
Wed May 4 21:12:24 EDT 2005
querypk at gmail.com wrote:
> If this is the list.
>
> values = [ 0, 72, 0, 4, 9, 2, 0, 0, 42, 26, 0, 282,
> 23, 0, 101, 0, 0, 0, 0, 0]
>
> as we can see there are peaks in the list.that is 0,72,0 is a
> group(triangle) with peak 72.then 0, 4, 9, 2, 0, 0 with peak
> 9 and 0, 42, 26, 0 with 42 and so on...
> what I want is the left and right bound index of each bin(triangle).The
> list could as big as possible.So some heurestic algorithm which could
> first find max in the list and look for local maxima and minima and
> group its adjcent bounds.Then find next max and group the bins and so
> on.
>
> so that we can get
>
> [[0,2],[2,7],[7,10],[10,13]]
> ( indexes of the bounds in the values list). so first group [0,2]
> correspond to 0,72,0 in the values list and so on...
> Hope I am clear.
Not exactly your output, but hopefully you can tailor it to your needs:
py> values = [0, 72, 0, 4, 9, 2, 0, 0, 42, 26, 0, 282, 23, 0, 101, 0, 0,
0, 0, 0]
py> def isnonzero((index, val)):
... return val != 0
...
py> import itertools
py> for nonzero, vals in itertools.groupby(enumerate(values), isnonzero):
... if nonzero:
... vals = list(vals)
... start = vals[0][0] - 1
... end = vals[-1][0] + 1
... print [start, end], "values: ", values[start:end+1]
...
[0, 2] values: [0, 72, 0]
[2, 6] values: [0, 4, 9, 2, 0]
[7, 10] values: [0, 42, 26, 0]
[10, 13] values: [0, 282, 23, 0]
[13, 15] values: [0, 101, 0]
Note that the real work is done by itertools.groupby. Zero terms are
grouped together and ignored; non-zero terms are gathered together in lists.
STeVe
More information about the Python-list
mailing list