fork download
  1. #!python3
  2.  
  3. import itertools
  4.  
  5. def three_sum(listnum):
  6.  
  7. possibility = itertools.combinations(listnum, 3)
  8. list_res = []
  9.  
  10. for pos in possibility:
  11. sum = 0
  12. for num in pos:
  13. sum += num
  14. if sum == 0:
  15. list_res.append(pos)
  16.  
  17. for i,l in enumerate(list_res):
  18. list_res[i] = tuple(sorted(l))
  19. list_res = set(tuple(list_res))
  20.  
  21. for i in list_res:
  22. for j in i:
  23. print(str(j)+' ', end='')
  24. print()
  25.  
  26. print('----------------------------------------------')
  27. three_sum([9, -6, -5, 9, 8, 3, -4, 8, 1, 7, -4, 9, -9, 1, 9, -9, 9, 4, -6, -8])
  28. print('----------------------------------------------')
  29. three_sum([4, 5, -1, -2, -7, 2, -5, -3, -7, -3, 1])
  30. print('----------------------------------------------')
  31. three_sum([-1, -6, -3, -7, 5, -8, 2, -8, 1])
  32. print('----------------------------------------------')
  33. three_sum([-5, -1, -4, 2, 9, -9, -6, -1, -7])
Success #stdin #stdout 0.01s 27664KB
stdin
Standard input is empty
stdout
----------------------------------------------
-4 1 3 
-5 -4 9 
-8 1 7 
-4 -4 8 
-9 1 8 
-5 1 4 
----------------------------------------------
-7 2 5 
-3 1 2 
-3 -2 5 
-3 -1 4 
-5 1 4 
----------------------------------------------
-3 1 2 
-7 2 5 
-6 1 5 
----------------------------------------------
-1 -1 2 
-5 -4 9