【问题标题】:find all possible combo pair in the list whose sum=0 in python using a dict使用dict在python中找到sum = 0的列表中所有可能的组合对
【发布时间】: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


【解决方案1】:
def pairsum(l):
    d = {}
    for i in l:
        if i not in d: d[i] = 0
        d[i] += 1
    for i in l:
        if i in d and (-i) in d:
            pair = f"{min(i,-i)} {max(i,-i)}"
            a,b = d[i],d[-i]
            if i != -i:
                for k in range(a*b):
                    print(pair)
                del d[i]
                del d[-i]
            else:
                for k in range(int(a*(a-1)/2)):
                    print(pair)
                del d[0]

问题是您可以将每个整数 = i 与其他每个 = -i 组合在一起,这意味着有 amount(i)*amount(-i) 对。零是一种特殊情况,因为您可以将每个零相互组合,但不能将同一个零与自身组合,这会产生n(n-1)/2 的可能性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-14
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多