-
Notifications
You must be signed in to change notification settings - Fork 12
/
maxima_good.py
77 lines (62 loc) · 1.87 KB
/
maxima_good.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Solution 1, only fixes the bugs without addressing the special cases
def find_maxima_1(x):
"""Find local maxima of x.
Example:
>>> x = [1, 2, 3, 1, 4, 3]
>>> find_maxima(x)
[2, 4]
If in a local maximum several elements have the same value,
return the rightmost index.
Example:
>>> x = [1, 2, 2, 2, 1]
>>> find_maxima(x)
[3]
Input arguments:
x -- 1D list of numbers
Output:
idx -- list of indices of the local maxima in x
"""
idx = []
for i in range(len(x)):
# `i` is a local maximum if the signal decreases before and after it
# WARNING: when `i` is at the limits of the list, check it decreases
# only in the direction where it is defined
if (i == 0 or x[i-1] < x[i]) and (i+1 == len(x) or x[i+1] < x[i]):
idx.append(i)
return idx
# Solution 2, more complex solution that considers the special cases
# XXX I'm pretty sure there exist a more elegant and concise solution,
# to be addressed in the refatoring step once the tests pass!
def find_maxima_2(x):
"""Find local maxima of x.
Example:
>>> x = [1, 2, 3, 1, 4, 3]
>>> find_maxima(x)
[2, 4]
If in a local maximum several elements have the same value,
return the rightmost index.
Example:
>>> x = [1, 2, 2, 2, 1]
>>> find_maxima(x)
[3]
Input arguments:
x -- 1D list of numbers
Output:
idx -- list of indices of the local maxima in x
"""
idx = []
up = False
down = False
for i in range(len(x)):
if i == 0 or x[i-1] < x[i]:
up = True
elif x[i-1] > x[i]:
up = False
# if x[i-1] == x[i], no change
if i+1 == len(x) or x[i+1] < x[i]:
down = True
elif x[i+1] > x[i]:
down = False
if up and down:
idx.append(i)
return idx