【发布时间】:2020-07-11 20:11:28
【问题描述】:
打印的方式是,较小的数字应该先打印后打印。 除了两个,所有测试用例都通过了。 代码背后的想法是将数字及其频率存储在字典中,然后遍历字典并检查 -(number) 如果存在,则将数字打印为频率并将其频率设为 0
def pairSum0(l):
if len(l)==0:
return
map = {}
for num in l: #to store the freq of each number
if num in map:
map[num] += 1
else:
map[num] = 1
for i in map:
if -i in map and map[i]!=0 and map[-i]!=0:
if map[i]==map[-i]:#k is getting the number of time the number is present
k=map[i]
if map[i]<map[-i]:
k=map[-i]
else:
k=map[i]
for j in range(k):
if -i<i:
print(-i,i)
else:
print(i,-i)
map[i]=0
map[-i]=0
n=int(input())
l=list(int(i) for i in input().strip().split(' '))
pairSum0(l)
代码在哪里得到错误的结果。谁能帮我调试一下? 一个失败的测试用例: 6 0 0 0 0 -1 1 我的输出 0 0 0 0 0 0 0 0 -1 1 想要的输出: 0 0 0 0 0 0 0 0 0 0 0 0 -1 1
【问题讨论】:
-
你还没有问过问题。欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。
-
你可以提供一个测试用例。如果你提供一个失败的案例会更好。
-
您可能需要 0 的特殊情况,因为您认为 -i 和 i 不同的假设可能不适用。如果你想要不同的组合,只需从计数中计算出来。有公式。
-
对于多次出现的正数和负数,重复组合的数量也会不同。 itertools 组合可能对两者都有帮助
标签: python dictionary hashmap