fork download
  1. from collections import defaultdict
  2.  
  3. def find_pair_by_sum(list_id_value, _sum):
  4. idx_for_value = defaultdict(list)
  5. paired = []
  6. for idx, value in list_id_value:
  7. try:
  8. # find the index of corresponding (_sum - value)
  9. value2 = _sum - value
  10. idx2 = idx_for_value[value2].pop()
  11. paired.append(((idx2, value2), (idx, value)))
  12. except IndexError:
  13. # cannot find a matched pair
  14. idx_for_value[value].append(idx)
  15. rest = [(idx, value) for value in idx_for_value for idx in idx_for_value[value]]
  16. return paired, rest
  17.  
  18. L = [(0,1), (1,2), (2,1), (3,1), (4,0), (5,0), (6,3)]
  19.  
  20. B, rest = find_pair_by_sum(L, 2)
  21. C, D = find_pair_by_sum(rest, 1)
  22.  
  23. print('list = ', L)
  24. print('B = ', B)
  25. print('C = ', C)
  26. print('D = ', D)
Success #stdin #stdout 0.02s 10192KB
stdin
Standard input is empty
stdout
list =  [(0, 1), (1, 2), (2, 1), (3, 1), (4, 0), (5, 0), (6, 3)]
B =  [((0, 1), (2, 1)), ((1, 2), (4, 0))]
C =  [((5, 0), (3, 1))]
D =  [(6, 3)]