Skip to content

Instantly share code, notes, and snippets.

@SaiMun92
Created October 9, 2019 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SaiMun92/8c06a478a5ae5fb6cc434fd642567c24 to your computer and use it in GitHub Desktop.
Save SaiMun92/8c06a478a5ae5fb6cc434fd642567c24 to your computer and use it in GitHub Desktop.
Merged Sorted Array
import unittest
def merge_lists(my_list, alices_list):
merged_list_size = len(my_list) + len(alices_list)
merged_list = [None] * merged_list_size
current_index_alices = 0
current_index_mine = 0
current_index_merged = 0
while current_index_merged < merged_list_size:
is_my_list_exhausted = current_index_mine >= len(my_list)
is_alices_list_exhausted = current_index_alices >= len(alices_list)
if (not is_my_list_exhausted and
(is_alices_list_exhausted or
my_list[current_index_mine] < alices_list[current_index_alices])):
# Case: next comes from my list
# My list must not be exhausted, and EITHER:
# 1) Alice's list IS exhausted, or
# 2) the current element in my list is less
# than the current element in Alice's list
merged_list[current_index_merged] = my_list[current_index_mine]
current_index_mine += 1
else:
# Case: next comes from Alice's list
merged_list[current_index_merged] = alices_list[current_index_alices]
current_index_alices += 1
current_index_merged += 1
print(merged_list)
return merged_list
# Tests
class Test(unittest.TestCase):
def test_both_lists_are_empty(self):
actual = merge_lists([], [])
expected = []
self.assertEqual(actual, expected)
def test_first_list_is_empty(self):
actual = merge_lists([], [1, 2, 3])
expected = [1, 2, 3]
self.assertEqual(actual, expected)
def test_second_list_is_empty(self):
actual = merge_lists([5, 6, 7], [])
expected = [5, 6, 7]
self.assertEqual(actual, expected)
def test_both_lists_have_some_numbers(self):
actual = merge_lists([2, 4, 6], [1, 3, 7])
expected = [1, 2, 3, 4, 6, 7]
self.assertEqual(actual, expected)
def test_lists_are_different_lengths(self):
actual = merge_lists([2, 4, 6, 8], [1, 7])
expected = [1, 2, 4, 6, 7, 8]
self.assertEqual(actual, expected)
unittest.main(verbosity=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment