Advertisement
Programmin-in-Python

Returning the Pair of numbers whose sum is the closest to zero

Feb 2nd, 2021
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.42 KB | None | 0 0
  1. from itertools import permutations as perm
  2.  
  3. def closest_to_zero(arr):
  4.     L1, D1, found = perm(arr, 2), dict(), False
  5.  
  6.     for i in L1:
  7.         D1[sum(i)] = i
  8.  
  9.     L2 = [abs(i) for i in D1.keys()]
  10.     req_val = min(L2)
  11.  
  12.     while not found:
  13.         res_T1 = D1.get(req_val, "")
  14.         if any(res_T1):
  15.             return res_T1
  16.         else:
  17.             req_val = -req_val
  18.  
  19.     return res_T1
  20.  
  21. var = closest_to_zero([10,20,30,40,50,60,-1,-2,-3,-4,-5,-6])
  22. print(var)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement