fork download
  1. # Find pairs in a list that sum up to a given target k.
  2.  
  3. def find_pairs(l, k):
  4. toret = []
  5.  
  6. for i, x in enumerate(l):
  7. if x <= k:
  8. target = k - x
  9.  
  10. if target in l[i + 1:]:
  11. toret.append((x, target))
  12. # break
  13.  
  14. return toret
  15.  
  16.  
  17. if __name__ == "__main__":
  18. l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  19. print(l, "@", 3, " =", find_pairs(l, 3))
  20.  
  21. l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  22. print(l, "@", 8, " =", find_pairs(l, 8))
  23.  
  24. l = [14, 7, 3, 4]
  25. print(l, "@", 7, " =", find_pairs(l, 7))
  26.  
  27. l = [14, 7, 7, 4]
  28. print(l, "@", 14, " =", find_pairs(l, 14))
  29.  
  30. l = [14, 7, 0, 4]
  31. print(l, "@", 7, " =", find_pairs(l, 7))
  32.  
  33. l = [4, 14, 3, 2, 7]
  34. print(l, "@", 7, " =", find_pairs(l, 7))
  35.  
Success #stdin #stdout 0.02s 9152KB
stdin
Standard input is empty
stdout
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @ 3  = [(1, 2)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @ 8  = [(1, 7), (2, 6), (3, 5)]
[14, 7, 3, 4] @ 7  = [(3, 4)]
[14, 7, 7, 4] @ 14  = [(7, 7)]
[14, 7, 0, 4] @ 7  = [(7, 0)]
[4, 14, 3, 2, 7] @ 7  = [(4, 3)]