Mungai Martin Mungai Martin - 1 month ago 8
Python Question

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

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

[1,2,3]
and
[1,2,3,4]
should return
4


[4,66,7]
and
[66,77,7,4]
should return
77


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

Answer

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
    else:
        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