Anuvrat Tiku - 3 months ago 18x

Python Question

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

Answer

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.

Source (Stackoverflow)

Comments