Guest User

Untitled

a guest
Mar 22nd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. """
  4. I was asked this in an interview and am feeling right now as though I pretty
  5. much choked. Doing it after-the-fact to make myself feel better.
  6.  
  7. Given sorted lists of numbers A, B, merge them together into a new sorted list,
  8. omitting repeats.
  9. """
  10.  
  11. def get_merged_list(A, B):
  12.  
  13. seen = set()
  14. results = []
  15.  
  16. while True:
  17.  
  18. # if we've exahausted both, we're done:
  19. if not A and not B:
  20. return results
  21.  
  22. # we might have just _one_ list empty:
  23. if A:
  24. a = A[0]
  25. else:
  26. a = None
  27. if B:
  28. b = B[0]
  29. else:
  30. b = None
  31.  
  32. # three "outer cases":
  33. if a is None:
  34. c = B.pop(0)
  35. elif b is None:
  36. c = A.pop(0)
  37. else:
  38. # third case has three cases
  39. if a > b:
  40. c = B.pop(0)
  41. elif b > a:
  42. c = A.pop(0)
  43. else:
  44. # they are the same. pop both.
  45. B.pop(0)
  46. c = A.pop(0)
  47.  
  48. # we definitely have a 'c' at this point
  49.  
  50. # have we seen it already?
  51. if c in seen or (results and c == results[-1]):
  52. continue
  53.  
  54. results.append(c)
  55. seen.add(c)
  56.  
  57.  
  58. cases = [
  59. {
  60. 'A': [1, 3, 3, 4, 5, 6, 8, 8, 8, 10],
  61. 'B': [1, 10, 11],
  62. 'expected': [1, 3, 4, 5, 6, 8, 10, 11],
  63. },
  64.  
  65. {
  66. 'A': [-3, -2, 0, 9, 10, 100],
  67. 'B': [87, 88],
  68. 'expected': [-3, -2, 0, 9, 10, 87, 88, 100],
  69. },
  70.  
  71. {
  72. 'A': [],
  73. 'B': [],
  74. 'expected': [],
  75. },
  76.  
  77. {
  78. 'A': [0, 3],
  79. 'B': [2],
  80. 'expected': [0, 2, 3],
  81. },
  82. {
  83. 'A': [2],
  84. 'B': [0, 3],
  85. 'expected': [0, 2, 3],
  86. },
  87. ]
  88.  
  89. for case in cases:
  90. A = case['A']
  91. B = case['B']
  92. expected = case['expected']
  93. assert get_merged_list(A, B) == expected, 'wrong:' + expected
Add Comment
Please, Sign In to add comment