I'm just hoping if there's a way to simplify this recursive code that takes 2 sorted lists and combines the two together in a sorted manner (without actually having to re-sort them).

def merge (l1,l2):
    if len(l1) == 0 and len(l2) == 0:
        return []
    if len(l1) == 0:
        return l2
    if len(l2) == 0:
        return l1
    if l1[0] <= l2[0]:
        return [l1[0]] + merge(l1[1:], l2)
    if l2[0] <= l1[0]:
        return [l2[0]] + merge(l1, l2[1:])

Use the built-in heapq.merge:

heapq.merge(*iterables)

Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.