1D peak algorithm (correct implementation)

Click For Summary

Discussion Overview

The discussion revolves around the implementation and effectiveness of a 1D peak finding algorithm in programming. Participants explore various aspects of the algorithm, including its correctness, variable naming conventions, and the distinction between finding a single peak versus multiple peaks.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant questions whether the provided peak finder code is a "good" implementation and asks if the goal is to find all peak values or just one.
  • Several participants discuss the importance of variable naming, suggesting that using common English words like 'array' can lead to unexpected behavior in code.
  • Another participant shares a personal anecdote about encountering issues with variable names in different programming languages, emphasizing the need for careful naming practices.
  • A participant proposes an alternative approach to finding peaks by suggesting a method to identify all values that are greater than their surrounding values, indicating a desire for a more comprehensive peak finding solution.
  • Some participants express uncertainty about the necessity of finding all peaks versus just one, with one noting that the algorithm's efficiency could be impacted by the approach taken.
  • Another participant mentions the trade-off between using a more efficient algorithm with a logarithmic time complexity versus a brute force method with linear time complexity for finding multiple peaks.

Areas of Agreement / Disagreement

Participants express differing views on the implementation of the peak finder algorithm and the best practices for variable naming. There is no consensus on whether the goal should be to find all peaks or just one, and the discussion remains unresolved regarding the optimal approach to peak finding.

Contextual Notes

Some participants highlight limitations in the current implementation, such as the handling of empty arrays and the need for clearer definitions of what constitutes a peak. There are also unresolved questions about the efficiency of different algorithms for peak finding.

Arman777
Insights Author
Gold Member
Messages
2,163
Reaction score
191
Python:
array_values = [[0], [0,0], [1,2], [3,1,2], [1,2,3], [4,6,2,1], [8,9,0,2,1]]

def peakfinder(xarray):
    if len(xarray) == 0:
        print("You entered an empty error !")
        raise ValueError
    if len(xarray) == 1:
        return xarray[0]
    if len(xarray) == 2:
        return max(xarray)
    mid_element_index = len(xarray) // 2
    mid_element = xarray[mid_element_index]
    if mid_element >= xarray[mid_element_index + 1] and mid_element >= xarray[mid_element_index - 1] :
        return mid_element
    elif mid_element < xarray[mid_element_index + 1]:
        return xarray[mid_element_index + 1:]
    else:
        return xarray[ :mid_element_index]

for xarray in array_values:
    while type(xarray) != int:   
        xarray = peakfinder(xarray)
    print("The peak value is", xarray)

Is this a "good" 1D peak finder code ? Also I have another problem. In the peak finder case do we have to find all the peak values or just one peak value ?

Also in my code I didnt like `while type(array) != int:`, but I couldn't come up with something clever :(

Thanks
 
Last edited:
Technology news on Phys.org
I don't know any clever way but did notice the variable name 'array'. The best practices guide will tell you programmers shy away from valid english words when selecting variable names.

The reasoning is that it can introduce some pretty strange behavior in your code if it happens to be a keyword in the language.

There was a recent cautionary story of a guy who got the license plate ‘null’ for his car thinking that plate readers won't be able to track him instead he now got all the ticket infractions for all unreadable plates ie they were assigned the value of null too and so by association he now owned those tickets.

xarray or array1 would be better choices.
 
  • Like
Likes   Reactions: StoneTemplePython, Wrichik Basu and Arman777
jedishrfu said:
I don't know any clever way but did notice the variable name 'array'. The best practices guide will tell you programmers shy away from valid english words when selecting variable names.

The reasoning is that it can introduce some pretty strange behavior in your code if it happens to be a keyword in the language.

There was a recent cautionary story of a guy who got the license plate ‘null’ for his car thinking that plate readers won't be able to track him instead he now got all the ticket infractions for all unreadable plates ie they were assigned the value of null too and so by association he now owned those tickets.

xarray or array1 would be better choices.
Thanks I ll be more careful
 
jedishrfu said:
I don't know any clever way but did notice the variable name 'array'. The best practices guide will tell you programmers shy away from valid english words when selecting variable names.

The reasoning is that it can introduce some pretty strange behavior in your code if it happens to be a keyword in the language.

There was a recent cautionary story of a guy who got the license plate ‘null’ for his car thinking that plate readers won't be able to track him instead he now got all the ticket infractions for all unreadable plates ie they were assigned the value of null too and so by association he now owned those tickets.

xarray or array1 would be better choices.
This became a major problem when I started with Python. In java, for example, I used str for string, which is a keyword in Python. I have several other standard variable names, which turned out to be functions in Python.
 
My experience was a weird one. Early mainframe Basic interpreters had a function called tst() which I think tested the string values for numeric data (can't remember and can't find via google).

I coded a loop:

for i = 1 to z step 10

and later changed the variable 'z' to something more descriptive 't' so that it read

for i = 1 to t step 10

However, to my great surprise, I got an error saying: "Invalid use of the tst() function expecting '('. "

Apparently, the interpreter removed the spaces during parsing and saw this line instead

fori=1totstep10 and parsed it as for,i,=,1,to,tst ...stop...error...expecting a parenthesis
 
  • Like
Likes   Reactions: Wrichik Basu and Arman777
Wrichik Basu said:
This became a major problem when I started with Python. In java, for example, I used str for string, which is a keyword in Python. I have several other standard variable names, which turned out to be functions in Python.
str is a big problem. I think array is generally not a problem, however as @jedishrfu said I shouldn't use it. I was using "sum" in the loops but it was a keyword so that was a problem for me..

jedishrfu said:
My experience was a weird one. Early mainframe Basic interpreters had a function called tst() which I think tested the string values for numeric data (can't remember and can't find via google).

I coded a loop:

for i = 1 to z step 10

and later changed the variable 'z' to something more descriptive 't' so that it read

for i = 1 to t step 10

However, to my great surprise, I got an error saying: "Invalid use of the tst() function expecting '('. "

Apparently, the interpreter removed the spaces during parsing and saw this line instead

fori=1totstep10 and parsed it as for,i,=,1,to,tst ...stop...error...expecting a parenthesis
I guess that's C right ? Its interesting ...
Arman777 said:
Also I have another problem. In the peak finder case do we have to find all the peak values or just one peak value ?
So what about this ? any ideas ?
 
[CODE lang="python" title="Real recursive version"]array_values = [[0], [0,0], [1,2], [3,1,2], [1,2,3], [4,6,2,1], [8,9,0,2,1]]

def peakfinder(xarray):
if len(xarray) == 0:
print("Error! You entered an empty array ")
raise ValueError
if len(xarray) == 1:
return xarray[0]
if len(xarray) == 2:
return max(xarray)
mid_element_index = len(xarray) // 2
mid_element = xarray[mid_element_index]
if mid_element >= xarray[mid_element_index + 1] and mid_element >= xarray[mid_element_index - 1] :
return mid_element
elif mid_element < xarray[mid_element_index + 1]:
return peakfinder(xarray[mid_element_index + 1:])
else:
return peakfinder(xarray[ :mid_element_index])

for xarray in array_values:
xarray = peakfinder(xarray)
print("The peak value is", xarray)[/CODE]
 
Last edited:
line 5 empty error --> empty array

If you're looking for the peak value and where its located:

Python:
def findnmax(xarray):
    maxvalue=0
    maxindex=0
    for i in range(len(xarray)):
       if xarray[i]>maxvalue:
          maxvalue=xarray[i]
          maxindex=i

    return (maxindex,maxvalue)

then this code might work.
 
jedishrfu said:
line 5 empty error --> empty array

If you're looking for the peak value and where its located:

Python:
def findnmax(xarray):
    maxvalue=0
    maxindex=0
    for i in range(len(xarray)):
       if xarray[i]>maxvalue:
          maxvalue=xarray[i]
          maxindex=i

    return (maxindex,maxvalue)

then this code might work.
I think that's a max value of an array, max can be also peak value but not necessarily.
 

Attachments

  • #10
jedishrfu said:
line 5 empty error --> empty array
Thanks !
 
  • #11
Okay I got it. Perhaps you can amend the loop in my code to find the case where the value is greater than the maxvalue and the values surrounding it are less and then adding the index of that value to a new array.

My code finds the highest value and thus by the definitions of the project its > the surrounding values.

But what you really want is a list of all values on the hills of the curve.
 
  • #12
Great exercise though.
 
  • Like
Likes   Reactions: Arman777
  • #13
jedishrfu said:
But what you really want is a list of all values on the hills of the curve.
I guess in peak find algorithm, finding all the peaks are optional. I mean the algorithm that I use has a O(logN) runtime and definitely finds a peak value. We can check each number to find peak points but that would have O(n) time complexity.

The important point is minimize the time complexity. However "if we wanted to find more than one peak or all the peaks" then is it better to use faster version of the algorithm and do some tricks on the array to keep searching or using brute force.
 
  • #14
jedishrfu said:
Great exercise though.
Indeed
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 10 ·
Replies
10
Views
1K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
4
Views
2K
Replies
9
Views
3K
Replies
55
Views
7K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 29 ·
Replies
29
Views
4K