Search code examples
pythonmathematical-optimization

Python list index out of range - finding local maxima


I have a dataset and am trying to work out where there are peaks in the data; a data point with a higher value than the point before and after it.

I have code which works for one dataset but now transferring it to another dataset brings up index out of range error for certain lines.

The code I have is:

for line in file.readlines():
    peaks.append(0)
    line = line.split(',')
    time.append(float(line[0]))
    TP.append(float(line[3]))
    level.append(float(line[5]))


for i in range(len(level)-1):
    i = i + 1
    if (level[i] > level[i-1]) and (level[i] > level[i+1]):
        peaks[i] = 1
        noPeaks = noPeaks +1

print noPeaks

Yet for one line (so far) it says data is out of range - visually inspecting the data doesn't suggest this - the value is higher than the previous value but lower than the next so on a rising limb of the graph.

Any help would be great!


Solution

  • I cannot see your loop but the (level[i] > level[i+1]) suggests that you are forgetting to put

    for i in range(1,len(list)-1)
    

    key to note there is that -1 since you're doing that +1 and the range only goes to max-1 anyway.

    Starting your loop at 0 would not throw an out of bounds error since list[-1] is perfectly legal in python. however, i dont think you want your first comparison to be list[-1] > list[0]


    Due to edit, You do not need to do the

    i = i + 1

    line in you're code, you will hit the length of the list because the for loop will also increment, causing an out of bounds error. Remove that line and it should work.