Python (128 137 136)
Damn you, itertools.permutations
, for having such a long name!
Brute force solution. I'm surprised it's not the shortest: but I guess itertools
ruins the solution.
Ungolfed:
import itertools
initial_set=map(int, input().split())
ans=[]
for length in range(1, len(x)+1):
for subset in itertools.permutations(initial_set, length):
if sum(subset)==0:
ans+=str(sorted(subset))
print set(ans)
Golfed (ugly output):
from itertools import*
x=map(int,input().split())
print set(`sorted(j)`for a in range(1,len(x)+1)for j in permutations(x,a)if sum(j)==0)
Golfed (pretty output) (183):
from itertools import*
x=map(int,input().split())
print `set(`sorted(j)`[1:-1]for a in range(1,len(x)+1)for j in permutations(x,a)if sum(j)==0)`[5:-2].replace("'","\n").replace(",","")
import itertools as i
: importing the itertools module and calling it i
x=map(int,input().split())
: seperates the input by spaces, then turns the resulting lists' items into integers (2 3 -5
-> [2, 3, -5]
)
set(sorted(j)
for a in range(1,len(x)+1)for j in i.permutations(x,a)if sum(j)==0):
Returns a list of all subsets in x
, sorted, where the sum is 0, and then gets only the unique items
(set(...)
)
The graves (`) around sorted(j)
is Python shorthand for repr(sorted(j))
. The reason why this is here is because sets in Python cannot handle lists, so the next best thing is to use strings with a list as the text.
1Do we have to worry about uniqueness if the input contains non-unique numbers? In other words, how many results do I have to print for the input
3 3 -3 -3
? – Keith Randall – 2012-10-10T04:03:06.527@Keith. By convention, sets consist of distinct elements that appear at most once. Multisets can have elements that appear more than once. http://en.wikipedia.org/wiki/Multiset
– DavidC – 2012-10-10T07:15:26.1034@DavidCarraher, OP mixes terminology by talking about subsets of lists. – Peter Taylor – 2012-10-10T07:18:57.457
@PeterTaylor Thanks. Good point. – DavidC – 2012-10-10T07:29:10.023