Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion maxima.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,20 @@ def find_maxima(x):
idx -- list of indices of the local maxima in x
"""

if not isinstance(x, list):
raise ValueError

if not all(isinstance(_x, (int, float)) for _x in x):
raise ValueError

idx = []
for i in range(len(x)):
# `i` is a local maximum if the signal decreases before and after it
if x[i-1] < x[i] and x[i+1] < x[i]:
if (
(i == 0 and x[i + 1] < x[i])
or (i == len(x)-1 and x[i - 1] < x[i])
or (0 < i < len(x)-1 and x[i - 1] < x[i] and x[i + 1] < x[i])
):
idx.append(i)

return idx
41 changes: 41 additions & 0 deletions test_maxima.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import maxima

import pytest


def test_left_boundary():
inp = [1, 0]
assert maxima.find_maxima(inp) == [0]


def test_right_boundary():
inp = [0, 1]
assert maxima.find_maxima(inp) == [1]


def test_both_boundaries():
inp = [2, 0, 1]
assert maxima.find_maxima(inp) == [0, 2]


def test_both_boundaries_oob():
inp = [1, 0, 2]
assert maxima.find_maxima(inp) == [0, 2]


def test_characters():
inp = "bca"
with pytest.raises(ValueError):
maxima.find_maxima(inp)


def test_characters2():
inp = ["b", "c", "a"]
with pytest.raises(ValueError):
maxima.find_maxima(inp)


def test_non_numeric():
inp = [None, [], "a", 5]
with pytest.raises(ValueError):
maxima.find_maxima(inp)