.
This can be done in O (n ^ 2). You do not need to sort this.
This is an extension of the problem that requires summing two numbers in x, and the trick is to use a hash table.
def triplets(l, total):
"""Sum of 3 numbers to get to total
Basically an extension of the 2 table
"""
l = set( l)
d = { }
for i in l:
remain = total - i
inside = {}
for j in l:
if i == j:
continue
inside[j] = remain -j
d[i] = inside
good = set()
for first, dic in d.iteritems():
for second, third in dic.iteritems():
if third in l:
good.add( tuple(sorted([first, second, third])) )
for each in good:
print each
triplets( [2, 3, 4, 5, 6], 3+4+5)
NOTE. We can use the quick sorting method for triplets, which will be O (1).
source
share