Finding subset of a set

Here is my program to Check if arr1 is a subset of arr2. But there is a bug when arr2 is not a subset of arr1. I am trying to implement the algorithm of it in python. But what is the best way to if it is not in the frequency table?

def isSubset(arr1, arr2):
    frequency = {}

    for i in range(0, len(arr1)):
        if arr1[i] in frequency:
            frequency[arr1[i]] = frequency[arr1[i]] + 1
        else:
            frequency[arr1[i]] = 1

    for i in range(0, len(arr2)):
        if frequency[arr2[i]] > 0:
            frequency[arr2[i]] -= 1
        else:
            return False

    return True

isSubset(['a'],['b']) # KeyError: 'b'

>Solution :

To fix the KeyError that your code is getting, you can use the dict.get method to return a default value of 0 when given a non-existing key.

Change:

if frequency[arr2[i]] > 0:

to:

if frequency.get(arr2[i], 0) > 0:

Leave a Reply