Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. """
  2. Given a list of integers and a single sum value,
  3. return the first two values (parse from the left please)
  4. in order of appearance that add up to form the sum.
  5. sum_pairs([11, 3, 7, 5], 10)
  6. # ^--^ 3 + 7 = 10
  7. == [3, 7]
  8.  
  9. sum_pairs([4, 3, 2, 3, 4], 6)
  10. # ^-----^ 4 + 2 = 6, indices: 0, 2 *
  11. # ^-----^ 3 + 3 = 6, indices: 1, 3
  12. # ^-----^ 2 + 4 = 6, indices: 2, 4
  13. # * entire pair is earlier, and therefore is the correct answer
  14. == [4, 2]
  15.  
  16. sum_pairs([0, 0, -2, 3], 2)
  17. # there are no pairs of values that can be added to produce 2.
  18. == None/nil/undefined (Based on the language)
  19.  
  20. sum_pairs([10, 5, 2, 3, 7, 5], 10)
  21. # ^-----------^ 5 + 5 = 10, indices: 1, 5
  22. # ^--^ 3 + 7 = 10, indices: 3, 4 *
  23. # * entire pair is earlier, and therefore is the correct answer
  24. == [3, 7]
  25. Negative numbers and duplicate numbers can and will appear.
  26.  
  27. NOTE: There will also be lists tested of lengths
  28. upwards of 10,000,000 elements. Be sure your code doesn't time out.
  29. """
  30. def sum_pairs(ints, s):
  31. pass
  32.  
  33. def assert_eq_or_none(tfunc_call_result, check_against, text):
  34. if check_against is None:
  35. assert tfunc_call_result is None, text
  36. else:
  37. assert tfunc_call_result == check_against, text
  38.  
  39. if __name__ == '__main__':
  40. args_cases = [
  41. ([1, 4, 8, 7, 3, 15], 8),
  42. ([1, -2, 3, 0, -6, 1], -6),
  43. ([20, -13, 40], -7),
  44. ([1, 2, 3, 4, 1, 0], 2),
  45. ([10, 5, 2, 3, 7, 5], 10),
  46. ([4, -2, 3, 3, 4], 8),
  47. ([0, 2, 0], 0),
  48. ([5, 9, 13, -3], 10),
  49. ([1] + [10 for x in range(9_999_998)] + [1], 2),
  50. ]
  51. test_cases = [
  52. ([1, 7], "Basic: {} should return [1, 7] for sum = 8"),
  53. ([0, -6], "Negatives: {} should return [0, -6] for sum = -6"),
  54. (None, "No Match: {} should return None for sum = -7"),
  55. ([1, 1], "First Match From Left: {} should return [1, 1] for sum = 2 "),
  56. ([3, 7], "First Match From Left REDUX!: {} should return [3, 7] for sum = 10 "),
  57. ([4, 4], "Duplicates: {} should return [4, 4] for sum = 8"),
  58. ([0, 0], "Zeroes: {} should return [0, 0] for sum = 0"),
  59. ([13, -3], "Subtraction: {} should return [13, -3] for sum = 10"),
  60. ([1, 1], "10m elements list, [1, 10, 10 ... 10, 1], should return [1, 1] for sum = 2")
  61. ]
  62. for args, case in zip(args_cases, test_cases):
  63. assert_eq_or_none(sum_pairs(*args), case[0], case[1].format(args[0]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement