First Double Peak

Source: May 2024, Task 4 (DTU 02002/02003). Study solution — not an official answer key.

Problem

A double peak at index i is strictly larger than both neighbors two steps away and one step away: values at i-2, i-1, i+1, and i+2.

Write first_double_peak(sequence) returning the first such index, or -1 if none. Indices near the ends (without two neighbors on each side) cannot be peaks.

Example
>>> first_double_peak([1.2, 2.4, 3.1, 2.9, 3.6, 2.3, 1.9, 2.4])
4

Approach

Loop i from 2 to len(sequence) - 3 and test the four neighbor comparisons.

Solution

Show solution Hide solution
Solution
def first_double_peak(sequence):
    for i in range(2, len(sequence) - 2):
        v = sequence[i]
        if (
            v > sequence[i - 2]
            and v > sequence[i - 1]
            and v > sequence[i + 1]
            and v > sequence[i + 2]
        ):
            return i
    return -1