2
\$\begingroup\$

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:])
Snowbody
8,66225 silver badges50 bronze badges
asked May 4, 2015 at 21:16
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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.

answered May 4, 2015 at 21:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.