Python 代码中的错误

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

有一个整数数组。还有不相交的集合 A 和 B,每个集合都包含整数。你喜欢集合 A 中的所有整数,不喜欢集合 B 中的所有整数。你的初始幸福感是 0。对于数组中的每个整数,如果 i 在 A 中,你的幸福感加 1。如果我在B,你的幸福感就会加-1。否则,你的幸福感不会改变。最后输出你最后的幸福。

输入格式

第一行包含由空格分隔的整数 n 和 m。 第二行包含 n 个整数,即数组的元素。 第三行和第四行分别包含 m 个整数 A 和 B。

输出格式

输出一个整数,即你的总幸福感。

输入样本

3 2

1 5 3

3 1

5 7

样本输出

1

有人可以解释一下这个解决方案有什么问题吗?它通过了一些测试,但在其他测试中失败了。

input()
array = set(input().split())
set1 = set(input().split())
set2 = set(input().split())
res = len(set1 & array) - len(set2 & array)
print(res)
python set
3个回答
4
投票

问题在于您将输入转换为集合,这反过来又删除了重复项。如果您的输入中有重复的值,那么您只需在所得幸福值上加/减 1。如果这是正确的,那么您的代码就没有问题。如果没有,那么您应该使用列表而不是集合。

代码可能是这样的:

# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# Now we use some list comprehension to get the happiness result
res = sum([1 for elem in array if elem in list1]) - sum([1 for elem in array if elem in list2])

第一个和累加正点,第二个和累加负点。它适用于多次出现,每次加/减一分。

编辑

更清晰的方法,理解 for 循环

# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# We create a variable res which will store the resulting happiness, initially 0
res = 0
# Now we iterate through the elements in array and check wheter they should add or substract
for elem in array:
    # If the element is in list1, we add 1 to res
    if elem in list1:
        res += 1
    # If the element is in list2, we substract 1 from res
    elif elem in list2:
        res -= 1

0
投票

我将列表 A 和 B 的输入作为一般列表。我想使用如下列表理解在一行中获得幸福。在我将 print 和 "happiness =" 合并在一行中之后。显然,这是使代码更快的解决方案。

input()
my_array = input().split()
listA=list(input().split())
listB=list(input().split())

print (sum(1 for data in my_array if data in listA)+sum(-1 for data in my_array if data in listB))

0
投票

如果你使用set,它会报错。因为它去掉了重复的元素

© www.soinside.com 2019 - 2024. All rights reserved.