Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading