MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / peak

Function peak

divide_and_conquer/peak.py:14–48  ·  view source on GitHub ↗

Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4

(lst: list[int])

Source from the content-addressed store, hash-verified

12
13
14def peak(lst: list[int]) -> int:
15 """
16 Return the peak value of `lst`.
17 >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
18 5
19 >>> peak([1, 10, 9, 8, 7, 6, 5, 4])
20 10
21 >>> peak([1, 9, 8, 7])
22 9
23 >>> peak([1, 2, 3, 4, 5, 6, 7, 0])
24 7
25 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2])
26 4
27 """
28 # middle index
29 m = len(lst) // 2
30
31 # choose the middle 3 elements
32 three = lst[m - 1 : m + 2]
33
34 # if middle element is peak
35 if three[1] > three[0] and three[1] > three[2]:
36 return three[1]
37
38 # if increasing, recurse on right
39 elif three[0] < three[2]:
40 if len(lst[:m]) == 2:
41 m -= 1
42 return peak(lst[m:])
43
44 # decreasing
45 else:
46 if len(lst[:m]) == 2:
47 m += 1
48 return peak(lst[:m])
49
50
51if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected