检查严格超集[Hackerrank问题]

问题描述 投票:0回答:2

所以我一直在解决黑客排名问题,并且遇到了一个非常奇怪的问题,这个问题已经困扰我几个小时了。 请参考这里的问题: 严格超集 Hackerrank 问题

下面是我的代码:

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)

当我在 hackerrank 上输入此内容时,它适用于除最后一个测试用例之外的所有情况。 经过观察,我得出的结论是,我的代码“可能不会”适用于最后一次比较返回 True 的情况,无论之前的比较如何。 我尝试更新我的代码(我发布的代码是更新的代码),通过在找到第一个 False 实例后立即退出,但无济于事。 这是输入的链接,用于我遇到问题的最后一个测试用例

所以基本上,这应该在第一个 False 实例上退出,但似乎并非如此。 请帮助我。非常感谢!

python set
2个回答
2
投票

这个程序有两个缺陷:首先,存在一个潜在的未处理的边缘情况,即两个集合的长度可能相等。这可以在您的第一个条件中进行调整,将其设为

<=
而不仅仅是
<

此外,当你设置

res = s.issuperset(a)
时,你需要在
res
为False时中断,因为在下一次迭代中,结果可能会再次被覆盖为
True
,这是你不希望的。

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)

在一个完全不相关的注释中,我无法控制自己,并尽可能合理地缩小了这个问题的解决方案。这也是应对挑战的有效解决方案:

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()))]
)))

0
投票

我的解决方案更短一些,听起来更容易阅读。如果您将 A 定义为 B 的严格超集,您将具有以下属性:

减法 B-A 将是非空的,并且 A-B 将是空的。用Python写的,你有这个:

A = set(input().split())
n = int(input())
N = [set(input().split()) for _ in range(n)]

print(all([(not s-A and A-s) for s in N]))```

An even better better implementation would be using the strictly less than comparison which [can be used to check for super sets too][1]

updating the last line, we have:

```python
print(all([s<A for s in N]))
© www.soinside.com 2019 - 2024. All rights reserved.