0

Given a large list of fluctuating values, how do you determine all local min values? Not using numpy. Local minimum means all values in a list that are the troughs of a function.

List_y = [23, 8, -7, 57, 87, 6]

I would like:

New_list = [-7, 6]
vaultah
  • 44,105
  • 12
  • 114
  • 143
John Gubba
  • 5
  • 1
  • 5

2 Answers2

5
def local_min(ys):
    return [y for i, y in enumerate(ys)
            if ((i == 0) or (ys[i - 1] >= y))
            and ((i == len(ys) - 1) or (y < ys[i+1]))]


>>> local_min([23, 8, -7, 57, 87, 6])
[-7, 6]
>>> local_min([23, 6, 6, 6, 42])
[6]
>>> local_min([6, 6, 4])
[4]
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
3

I'm a big fan of iterating over these problems in stages.

l = [23, 8, -7, -7, 57, 87, 6]

# Remove identical neighbors
# l becomes [23, 8, -7, 57, 87, 6]
l = [x for x,y in zip(l[0:], l[1:]) if x != y] + [l[-1]]

# Append positive infinity to both endpoints
# l becomes [inf, 23, 8, -7, 57, 87, 6, inf]
l = [float("inf")] + l + [float("inf")]

# Retain elements where each of their neighbors are greater than them.
# l becomes [-7, 6]
l = [y for x, y, z in zip(l[0:], l[1:], l[2:]) if x > y < z]
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • i think it's underappreciated :) – JuniorCompressor Apr 13 '15 at 20:40
  • As I understand it from its definition, the minima isn't strictly _smaller_ than its neighbors, but may be equal to (either of) them. Thus, I think your _Remove identical neighbors_ step may be eliminated, and the code be: `>>> l = [23, 8, -7, -7, 57, 87, 6]` >>> l = [float("inf")] + l + [float("inf")] `>>> l = [y for x, y, z in zip(l[0:], l[1:], l[2:]) if x >= y <= z]` >>> l `[-7, -7, 6]` – boardrider Apr 14 '15 at 09:31
  • @boardrider: Then `3 4 4 4 3` would report `3 4 3` which is wrong. In addition, in the comments, John said that he was fine with only getting `-7, -6` from the input you suggest. I agree that a more accurate solution would have `-7 -7 6`, but creating that answer is harder with list comprehensions. – Bill Lynch Apr 14 '15 at 12:08
  • @Bill, why is `3 4 3` wrong (if we take the definition of minimal to be <=) ? `3` is the minimal of `None and 3`, `4` is the minimal of `4 4 4`, and `3` is the minimal of `3 and None`. What don't I get? – boardrider Apr 14 '15 at 22:15
  • @boardrider: John never fully clarified what he meant by minima. It's certainly possible that the definition you're suggesting is what he was looking for. Personally, I'm considering this more like a function. So we can't just look at neighbors. – Bill Lynch Apr 14 '15 at 22:35