user5988042
user5988042

Reputation:

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

Upvotes: 0

Views: 109

Answers (2)

furas
furas

Reputation: 142985

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

Upvotes: 3

Eric
Eric

Reputation: 75

The current code will return True for each element in arr2, what you're looking for is if arr1 in arr2:

Upvotes: 0

Related Questions