20. Merge two sorted lists
Write a function merge(a, b) that takes two lists of numbers, each already sorted from smallest to largest, and
returns one new list with all the items of both, also sorted from smallest to largest.
Don't call sorted() or .sort(). Both lists are already in order, so you can walk through them side by side and
always take the smaller of their front items.
Keep every item, repeats included: a number that is in both lists appears twice in the result. Either list, or both, can be empty.
Example 1
a = [1, 4, 9], b = [2, 3, 10][1, 2, 3, 4, 9, 10]Example 2
a = [], b = [5, 6][5, 6]Example 3
a = [2, 2], b = [1, 2][1, 2, 2, 2]Constraints
aandbeach have 0 to 50 whole numbers.- Each list is sorted from smallest to largest, and can hold repeats.
Submit also runs 4 more tests you can't see.
Practises While Loops (lesson 14).
- Keep one index into each list,
i = 0andj = 0. Each points at the smallest item of its list not used yet. - While both lists have items left (
i < len(a) and j < len(b)), comparea[i]withb[j], append the smaller one, and move that index on by one. On a tie, take either: both copies end up in the result. - When one list runs out, the rest of the other is sorted and no smaller than anything taken: add it with
result + a[i:] + b[j:]. That also covers an empty list.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def merge(a, b):
"""Merge two sorted lists into one sorted list.
a, b: list of int, each sorted smallest first;
either may be empty
Returns: list of int, all their items, sorted, made
without sorted() or .sort()
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.