Data
arr = [7, 12, 13, 8, 2, 16, 24, 11, 5, 1]
A one-liner:
One line should be enough:
max_peak = max(x2 for x1, x2, x3 in zip(arr, arr[1:], arr[2:]) if x1 < x2 > x3)
In a loop
Maybe easier to understand when you are new to Python:
peak = float('-inf')
for x1, x2, x3 in zip(arr, arr[1:], arr[2:]):
if x1 < x2 > x3:
peak = max(peak, x2)
print(peak)
Output:
24
All peaks
You can also use a one-liner to get all peaks:
>>> [x2 for x1, x2, x3 in zip(arr, arr[1:], arr[2:]) if x1 < x2 > x3]
[13, 24]
and get the greatest one with max() on the result.
Explanation
Let's have a look at some of the components of the solution. I am working with Python 3 here, as everybody should. ;)
You can slice lists.
>>> arr = [7, 12, 13, 8, 2, 16, 24, 11, 5, 1]
This gives you all of the list but the first element:
>>> arr[1:]
[12, 13, 8, 2, 16, 24, 11, 5, 1]
Here its starts with element three:
>>> arr[2:]
[13, 8, 2, 16, 24, 11, 5, 1]
The zip() function zips multiple sequences together. To visualize what happens, you can convert the zip object into a list:
>>> list(zip(arr, arr[1:], arr[2:]))
[(7, 12, 13),
(12, 13, 8),
(13, 8, 2),
(8, 2, 16),
(2, 16, 24),
(16, 24, 11),
(24, 11, 5),
(11, 5, 1)]
Python supports tuple unpacking. This allows to assign individual names to all members of a tuple:
>>> x1, x2, x3 = (7, 12, 13)
>>> x1
7
>>> x2
12
>>> x3
13
Another nice feature is the comparison of more than two objects:
>>> 10 < 12 > 8
True
This is equivalent to:
>>> (10 < 12) and (12 > 8)
True
Python offers list comprehensions:
>>> [x * 2 for x in range(2, 6)]
[4, 6, 8, 10]
Generator expression work in a similar way but don't produce a list but an iterator and can be consumed without using lots of memory:
>>> sum(x * 2 for x in range(2, 6))
28
return _find_peak...in theelifparts.. But you'll still get bad result (at least notNone) :)