From array of numbers, find 3 numbers such that its Sum is Zero Problem solve using python

There are array of numbers from it we need to find 3 numbers whose sum should zero with minimum loops and minimum combinations. I did following code for it. Suggestions are most welcome.


from itertools import combinations
a=[-1,-1,2,4,5,0,-4,3,1,1,-2]
positive1=[]
negative1=[]
zero=[]

# Only two pair combination (two from positive and two from negative numbers) with one loop used. Last loop is checking negative and positive number to sum with pair Its combinations not permutations.
# Two combinations will reduce time.

for i in set(a):
    if i>=0:
        positive1.append(int(i))
      
    elif i<=0:
        negative1.append(int(i))


#non repeat combination not permutations
h1=list(combinations(positive1,2))
g1=list(combinations(negative1,2))


for h,g in zip(h1,g1):
    x=sum([h[0],h[1]])
    if -abs(x) in negative1:
        zero.append([h[0],h[1],-x])
    y=sum([g[0],g[1]])
    if abs(y) in positive1:
        zero.append([g[0],g[1],-y])
    
print(zero)

Note: For Analytical purpose if you want to add nodes(Graph Nodes or Items) whose price is more or less or equal like sum zero one can try Graph Database like Neo4j or relevant to optimize with fast analytics.

Leave a comment