Home > Back-end >  IndexError: list index out of range, python3
IndexError: list index out of range, python3

Time:01-24

The problem I try to solve is this: "Given an array of integers, find the pair of adjacent elements that has the largest product and return that product."

This is my code but it says that "IndexError: list index out of range"

def solution(inputArray):
    largest_product = 0
    x = 0
    y = 0
    length_of_array = len(inputArray)
    
    if(length_of_array < 2):
        return
    
    for i in range(len(inputArray)):
        x = inputArray[i]
        y = inputArray[i 1]
        
        if(x * y > largest_product):
            largest_product = x * y
            
    return largest_product


inputArray = [3, 6, -2, -5, 7, 3]

CodePudding user response:

you get IndexError: list index out of range because you try to access an item that doesn't exists - y = inputArray[i 1] = inputArray[6] = not exists

def solution(inputArray):
    largest_product = 0
    x = 0
    y = 0
    length_of_array = len(inputArray)

    if (length_of_array < 2):
        return

    for i in range(len(inputArray)-1):
        x = inputArray[i]
        y = inputArray[i   1]

        if (x * y > largest_product):
            largest_product = x * y

    return largest_product

you have an easier to do it using zip and `max:

max(x*y for x,y in zip(inputArray[:-1],inputArray[1:]))
  •  Tags:  
  • Related