diff --git a/hands_on/local_maxima_part2/local_maxima.py b/hands_on/local_maxima_part2/local_maxima.py index db89ba3..e505faa 100644 --- a/hands_on/local_maxima_part2/local_maxima.py +++ b/hands_on/local_maxima_part2/local_maxima.py @@ -1,10 +1,33 @@ -def find_maxima(x): - """Find local maxima of x. +def find_maxima(points): + """Find local maxima of points. Input arguments: - x -- 1D list of real numbers + points -- 1D list of real numbers Output: - idx -- list of indices of the local maxima in x + indices -- list of indices of the local maxima in points """ - return [] + indices = [] + plateau_idx = [] + + if not points: + print("No input given") + return [] + elif len(points) == 1: + return [0] + + if points[0] > points[1]: + indices.append(0) + for i in range(1, len(points)-1): + if points[i] > points[i+1] and points[i] > points[i-1]: + indices.append(i) + plateau_idx = [] + if points[i] == points[i+1]: + plateau_idx.append(i) + if points[i] > points[i+1] and plateau_idx: + indices.append(plateau_idx[0]) + plateau_idx = [] + + if points[-1] > points[-2]: + indices.append(len(points)-1) + return indices \ No newline at end of file diff --git a/hands_on/local_maxima_part2/test_local_maxima.py b/hands_on/local_maxima_part2/test_local_maxima.py index 316442d..d6561f5 100644 --- a/hands_on/local_maxima_part2/test_local_maxima.py +++ b/hands_on/local_maxima_part2/test_local_maxima.py @@ -23,8 +23,14 @@ def test_find_maxima_empty(): def test_find_maxima_plateau(): - raise Exception('not yet implemented') + values = [1, 2, 2, 1] + expected = [1] + maxima = find_maxima(values) + assert maxima == expected def test_find_maxima_not_a_plateau(): - raise Exception('not yet implemented') + values = [1, 2, 2, 3, 1] + expected = [3] + maxima = find_maxima(values) + assert maxima == expected diff --git a/local_maxima.py b/local_maxima.py new file mode 100644 index 0000000..154b290 --- /dev/null +++ b/local_maxima.py @@ -0,0 +1,17 @@ +def find_maxima(points): + indices = [] + + if not points: + print("No input given") + return [] + elif len(points) == 1: + return [0] + + if points[0] > points[1]: + indices.append(0) + for i in range(1, len(points)-1): + if points[i] > points[i+1] and points[i] > points[i-1]: + indices.append(i) + if points[-1] > points[-2]: + indices.append(len(points)-1) + return indices \ No newline at end of file