So I've been solving hackerrank problems, and I have encountered a pretty strange problem that's been bugging me for hours now. Kindly refer to the problem question here: Strict Superset Hackerrank Problem
Below is my code for this:
import sys
s = set(map(int, input().split()))
inp = int(input())
res = True
while(inp):
a = set(map(int, input().split()))
if len(s) < len(a):
res = False
print(res)
sys.exit()
if len(s) > len(a):
res = s.issuperset(a)
inp -= 1
print(res)
When I typed this on hackerrank, it works for all the cases except for the last test case. Upon observation, I came to a conclusion that my code "might not" work for cases where the last comparison returns True, regardless of the comparisons before. I tried updating my code(The one I posted is the updated one), by trying to exit as soon as I find the first instance of False, but to no avail. Here is the Link for the Input, for the last Test case that I've been facing a problem with
So Basically, this is supposed to exit on the first instance of False, but it seems to be not. Kindly help me out. Many thanks!
There were two gaps in this program: first, there is a potential unhandled edge case where the two sets could be equal length. This can be adjusted in your first conditional by making it <=
instead of just <
.
Additionally, when you set res = s.issuperset(a)
, you also need to break when res
is False, because in the next iteration, the result may be overridden to True
again, which you don't want.
s = set(map(int, input().split()))
inp = int(input())
res = True
while(inp):
a = set(map(int, input().split()))
if len(s) <= len(a):
res = False
print(res)
sys.exit()
if len(s) > len(a):
res = s.issuperset(a)
if not res:
break
inp -= 1
print(res)
On a totally unrelated note, I couldn't help myself, and minified the solution to this problem as much as I reasonably could. This is also a valid solution to the challenge:
superset = set(map(int, input().split()))
print(all(map(
lambda subset: len(superset) > len(subset) and superset.issuperset(subset),
[set(map(int, input().split())) for _ in range(int(input()))]
)))