Anuvrat Tiku
Anuvrat Tiku

Reputation: 1646

A simple 1-D peak finding program in python

A peak finding program in a 1-D python list which returns a peak with its index if for an index 'x' in the list 'arr' if (arr[x] > arr[x+1] and arr[x] > arr[x-1]). Special case Case 1 : In case of the first element. Only compare it to the second element. If arr[x] > arr[x+1], peak found. Case 2 : Last element. Compare with the previous element. If arr[x] > arr[x-1], peak found. Below is the code. For some reason it is not working in the case the peak is at index = 0. Its perfectly working for the peak in the middle and peak at the end. Any help is greatly appreciated.

import sys
def find_peak(lst):
    for x in lst:
        if x == 0 and lst[x] > lst[x+1]:
            print "Peak found at index", x
            print "Peak :", lst[x]
            return

        elif x == len(lst)-1 and lst[x] > lst[x-1]:
            print "Peak found at index", x
            print "Peak :", lst[x]
            return

        elif x > 0 and x < len(lst)-1:
            if  lst[x] > lst[x+1] and lst[x] > lst[x-1]:
                print "Peak found at index", x
                print "Peak :", lst[x]
                return

    else :
        print "No peak found"

def main():
    lst = []
    for x in sys.argv[1:]:
    lst.append(int(x))

    find_peak(lst)

if __name__ == '__main__':
    main()

Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 
Peak found at index 3
Peak : 4
Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 3
Peak found at index 3
Peak : 4
Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 4 3 2 1
No peak found

Upvotes: 2

Views: 269

Answers (2)

keiv.fly
keiv.fly

Reputation: 4035

x is a list element in your code and you are using it as an index.

you should write:

def find_peak(lst):
    for i,x in enumerate(lst):
        if i == 0 and x > lst[i+1]:
            print "Peak found at index", i
            print "Peak :", x
            return

        elif i == len(lst)-1 and x > lst[i-1]:
            print "Peak found at index", i
            print "Peak :", x
            return

        elif i > 0 and i < len(lst)-1:
            if  x > lst[i+1] and x > lst[i-1]:
                print "Peak found at index", i
                print "Peak :", x
                return

    else :
        print "No peak found"

Upvotes: 1

James
James

Reputation: 2711

Your issue lies in the initialization of your loop

for x in lst:

With this loop, for your last example, x will be 4, then 3, then 2, then 1.

By the looks of your code, it seems you intended to say:

for x in range(len(lst)):

This will iterate over the indices of the list rather than the values in the list. The reason your code even appeared to work was because in your test cases, the values of the list closely matched the indices of the list - consider more varied tests in the future.

Upvotes: 1

Related Questions