Mungai Martin Mungai Martin - 1 year ago 91
Python Question

IndexError: list index out of range - for i in arr1 and arr2

You are presented with two arrays, all containing positive integers. One of the arrays will have one extra number, see below:

should return

should return

My code:

def find_missing(arr1, arr2):
if len(arr1) != len(arr2):
for i in arr1 and arr2:
if arr1[i] != arr2[i]:
return i

Is producing this error:

Traceback (most recent call last): File "python", line 1,
in <module> File "python", line 4, in find_missing
IndexError: list index out of range

Answer Source

This could be one way of doing it:

def find_missing(arr1, arr2):

    # Set longer array to lst1, shorter to lst2 
    if len(arr1) > len(arr2):
        lst1 = arr1
        lst2 = arr2
        lst1 = arr2
        lst2 = arr1

    # Go through elements in longer list
    for element in lst1:

        # If this element is not in lst2, we found it, return result
        if element not in lst2:
            return element
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download