Search code examples
pythonlistcountlocalmaxima

Counting the numbers in a list that are larger than their neighbors


I want to find a peak in a list.

  1. I want to find if a number is bigger than his neighbors.
  2. if it is the first object in the list I want to check only if he is bigger than the one after him.
  3. if it is the last object in the list I want to check the one before him.
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.


Solution

  • 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].