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