Python3: Zero-balanced Array

Codewars

codewars kata: www.codewars.com/kata/zero-balanced-array/python

An array is called zero-balanced if its elements sum to 0 and for each positive element n, there exists another element that is the negative of n. Write a function named ìsZeroBalanced that returns true if its argument is zero-balanced array, else return false. Note that an empty array will not sum to zero.

Tests

Test.describe("Basic tests")
Test.assert_equals(is_zero_balanced([3]),False)
Test.assert_equals(is_zero_balanced([-3]),False)
Test.assert_equals(is_zero_balanced([0,0,0,0,0,0]),True)
Test.assert_equals(is_zero_balanced([0,1,-1]),True)
Test.assert_equals(is_zero_balanced([]),False)
Test.assert_equals(is_zero_balanced([3,-2,-1]),False)
Test.assert_equals(is_zero_balanced([0]),True)
Test.assert_equals(is_zero_balanced([1,1,-2]),False)
Test.assert_equals(is_zero_balanced([-1,1,-2,2,-2,-2,-4,4]),False)
Test.assert_equals(is_zero_balanced([0,0, 0,0,0]),True)

Best solution

def is_zero_balanced2(arr):
    return bool(arr) and sum(arr) == 0 and all(-x in arr for x in arr if x > 0)

My Solution

def is_zero_balanced(arr):
    return True if arr and sorted([x for x in arr if x>0]) == sorted(map(lambda x: x*-1, [x for x in arr if x<0])) and sum(arr)==0 else False

My Comment

Firstly I was thinking about that for every positive number you have to find equal negative. So for [5,-5,-5] you should check that there is exactly one opposite for positive number. Unfortunately I completely forgot about one thing – you do not have to check uniqueness if you calculate sum of whole array.

Also from competitive solutions I have learned a new thing – function All ( docs.python.org/2/library/functions.html#all )