<p>我知道这是个老问题,但我也遇到了同样的问题,正如Cardin在<a href="https://stackoverflow.com/a/19936218/6205379">Malvolio's answer</a>的注释中所说,答案不能处理具有相同值的连续点,如<code>[1, 2, 3, 4, 4, 4, 3, 2, 1]</code>。我的实现可以处理这个问题。</p>
<p>尽管如此,它返回两个列表,其中包含最小和最大转折点的索引。</p>
<pre><code>def turning_points(array):
''' turning_points(array) -> min_indices, max_indices
Finds the turning points within an 1D array and returns the indices of the minimum and
maximum turning points in two separate lists.
'''
idx_max, idx_min = [], []
if (len(array) < 3):
return idx_min, idx_max
NEUTRAL, RISING, FALLING = range(3)
def get_state(a, b):
if a < b: return RISING
if a > b: return FALLING
return NEUTRAL
ps = get_state(array[0], array[1])
begin = 1
for i in range(2, len(array)):
s = get_state(array[i - 1], array[i])
if s != NEUTRAL:
if ps != NEUTRAL and ps != s:
if s == FALLING:
idx_max.append((begin + i - 1) // 2)
else:
idx_min.append((begin + i - 1) // 2)
begin = i
ps = s
return idx_min, idx_max
</code></pre>
<p>为了正确回答问题,转折点的数量计算如下:</p>
<pre><code>sum(len(x) for x in turning_points(X))
</code></pre>
<h2>示例</h2>
<p><a href="https://i.stack.imgur.com/2wJjq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2wJjq.png" alt="enter image description here"/></a></p>