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
            frequency[arr1[i]] = 1

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

    return True

isSubset(['a'],['b']) # KeyError: 'b'
Asked By: test tes



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.


if frequency[arr2[i]] > 0:


if frequency.get(arr2[i], 0) > 0:
Answered By: blhsing
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.