grilam14 grilam14 - 20 days ago 8
Python Question

Having trouble using "in" function to check for containment of one array in another

The current code is extremely short. If I understand the "in" function correctly, shouldn't the for loop only iterate and return True if both [1,3] is in [1,4,5]? Right now I am getting true for all of my tests. I feel like there is an easy fix to this, I just don't know.

I tried putting an if statement in-between the for and return lines but that still only returned true.

def innerOuter(arr1, arr2):
for arr1 in arr2:
return True
return False

Answer

You have to use if one_element in array

def innerOuter(arr1, arr2):
    for x in arr1:
        if x not in arr2:
            return False
    return True

innerOuter([1,3], [1,4,5]) # False
innerOuter([1,4], [1,4,5]) # True

Or you can use set() to check it

def innerOuter(arr1, arr2):
    return set(arr1).issubset(set(arr2))

innerOuter([1,3], [1,4,5]) # False
innerOuter([1,4], [1,4,5]) # True

The same:

def innerOuter(arr1, arr2):
    return set(arr1) <= set(arr2)

https://docs.python.org/2/library/sets.html#set-objects

Comments