Skip to content

Instantly share code, notes, and snippets.

@alberto-santini
Created November 25, 2018 21:06
Show Gist options
  • Save alberto-santini/9de98621f85cb5036756d6d379d95949 to your computer and use it in GitHub Desktop.
Save alberto-santini/9de98621f85cb5036756d6d379d95949 to your computer and use it in GitHub Desktop.
Detect local minima and maxima in a Python list
def flatten(a):
return sum(a, [])
def local_minima(a):
if len(a) < 2:
return list(range(len(a)))
lmin = True
curr = list()
local_minima = list()
for i, x in enumerate(a[:-1]):
if a[i + 1] == x and lmin:
curr.append(i)
if a[i + 1] < x:
lmin = True
curr = list()
if a[i + 1] > x:
if lmin:
local_minima.append(curr + [i])
lmin = False
if a[-1] < a[-2] or (lmin and a[-1] == a[-2]):
local_minima.append(curr + [len(a) - 1])
return flatten(local_minima)
def invert(a):
return [-x for x in a]
def local_maxima(a):
return local_minima(invert(a))
test = [
([1,2,3,2,3,2,1], [0,3,6]),
([1,2,3,2,2,3,2,1], [0,3,4,7]),
([4,3,2,3,4], [2]),
([1,2,1], [0,2]),
([1,2,1,2,1], [0,2,4]),
([2,1,1,1,1,2], [1,2,3,4]),
([2,1,1,1,0], [4]),
([1,1,1], [0,1,2]),
([1,2,3], [0]),
([3,2,1], [2]),
([1,2,2,2,1], [0,4]),
([1,2,1,2,1,2], [0,2,4]),
([3,2,1,1,1], [2,3,4]),
([1], [0]),
([], [])
]
for i, o in test:
l = local_minima(i)
print("In: {}; Expected: {}; Actual: {}; Passed: {}".format(i, o, l, l == o))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment