Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IndexError: list index out of range, python3

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading