min max of a list

Kent Johnson kent37 at tds.net
Fri May 6 14:00: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.

ISTM you just have to look for the valleys - places where the values change from descending to 
ascending. Here is a simple-minded way to do it:

def findPeaks(values):
     groups = []
     startIx = 0
     lastValue = values[0]
     ascending = True

     for i, value in enumerate(values[1:]):
         if value <= lastValue:
             ascending = False
         else:
             if not ascending:
                 # Switch from descending to ascending
                 groups.append( [startIx, i] )
                 startIx = i
                 ascending = True

         lastValue = value

     # Get the last group if any
     if i > startIx:
         groups.append( [startIx, i] )

     return groups


values = [  0,  72,   2,   4,   9,   2,   0,   0,  42,  26,   0, 282,
23,   0, 101, 0,   0,   0,   0,   0]

print findPeaks(values)

## prints:
[[0, 2], [2, 7], [7, 10], [10, 13], [13, 18]]

Kent



More information about the Python-list mailing list