有一个整数数组。还有不相交的集合A和B,每个集合包含整数。你喜欢集合A中的所有整数并且不喜欢集合B中的所有整数。你的初始幸福是0.对于数组中的每个整数,如果我在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)
答案 0 :(得分: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
答案 1 :(得分:0)
我将列表 A 和 B 的输入作为一般列表。我想使用如下列表理解在 1 行中获得快乐。在我将 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))