Python: Index Out Of Range when traversing a vector

1

I work in a function that should look for the element with the highest value in a vector, but I get an error when compiling, the code is the following:

def getVPPXSenialXMovXFilaMaximosMinimos(self, mov_canal, fila):
    line = [self.file.getVectorPorFilaPorSenial(mov_canal, fila)]
    i = 0
    while i < len(line):
        if line[i] >= line[i+1]:
            maxi = line[i]
        else:
            i += 1
    return maxi

The error always gives me on the fifth line.

    
asked by Sebastián Sosa 01.12.2018 в 03:02
source

1 answer

0

The problem is the line[i+1] when i gets to be the size of the list the +1 causes it to get out of the range of the list, be careful with what you have in the else because your function can fall into a loop infinite, you always have to add to one independently whether it fulfills the condition or not.

I suggest two possible solutions:

maxi = 0 
for d in line:
    if int(d) > maxi: 
        maxi = int(d)
 return maxi 

The other and shorter option is

line = [ int(d) for d in line] 
maxi = max(line) 
return maxi 

I'm assuming that you have a string of numbers online, if you have to compare characters you just have to remove the int of the code

    
answered by 01.12.2018 / 08:41
source