-1

i have 2 sets a=[3,4,5,5] b=[3,4,5,6,7,8,9] we have to find whether a is a subset of b?

a=[3,4,5,5] 
b=[3,4,5,6,7,8,9]
if(set(a).issubset(set(b))): 
    print('yes')
else:
    print('no')

this code print yes as it is ignoring copies of elements, example: it considers that 5 is occuring only single time in set 'a'

I want the answer to be 'no' as b has only one 5.

anadi
  • 63
  • 1
  • 6

3 Answers3

1

If you must do this without libraries and your lists are sorted you can perform the match using an iterator. Progress through the second set while advancing the first one when the values are the same. You will know that the first list is a subset of the second if you get through all of it (using the iterator)

def isSubset(setA,setB):
    iterA  = iter(setA)
    valueA = next(iterA,None)
    for valueB in setB:
        if valueA == valueB:
            valueA = next(iterA,None)
    return valueA is None

a=[3,4,5,5] 
b=[3,4,5,6,7,8,9]
print(isSubset(a,b)) # False

c=[3,4,5,5,5,6,7,8,9]
print(isSubset(a,c)) # True  

d=[3,4,5,5,5,6,7]
print(isSubset(b,d)) # False  

if the lists are not guaranteed to be sorted you can sort them at the begining of the function by adding:

setA,setB = sorted(setA),sorted(setB)

if you want to make this faster, you can add a condition to exit the loop as soon as the end of setA is reached or when a value in set B is greater than the current value of set A:

# at beginning of for loop:
if valueA is None or valueB > valueA: break
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

5 is occuring twice in a, but once in set(a). set(a)=(3,4,5) and set(b)=(3,4,5,6,7,8,9), therefore the answer is correct.

Hamza Hathoute
  • 438
  • 3
  • 12
0

Use the collections.Counter.

all(v >= 0 for v in (Counter(b) - Counter(a)).values())

This is True if a is a sub bag of b.

Dan D.
  • 73,243
  • 15
  • 104
  • 123