I want to find a peak in a list.
def peaks(lst):
num = 0
leni = len(lst)
print(leni)
for i in range(1,leni - 1):
if lst[i] > lst[i-1] and lst[i] > lst[i+1]:
num = num + 1
for i in range(leni):
print(i)
if i == 0:
if lst[i] > lst[i+1]:
num = num + 1
elif i == leni+1:
if lst[i] > lst[i-1]:
num = num + 1
return num
This code doesn't work when it should check the last object.
When I try [1,2,3]
I get 0
instead of 1
.
Hello and welcome to Stackoverflow!
Note that range(leni)
is a sequence of numbers from 0 to leni - 1
inclusive. So your condition i == leni+1
is never satisfied. You may replace it to i == leni - 1
.
Note also that you don't need a second loop. You may just replace it with
if lst[0] > lst[1]:
num = num + 1
if lst[-1] > lst[-2]:
num= num + 1
Here lst[-1]
is the same as lst[leni - 1]
and lst[-2]
is the same as lst[leni - 2]
.