how to use `heapq.merge`?

813 views Asked by At

Here's the snippet I've been trying:

>>> L1 = [i for i in range(10) if i % 2 == 0]
>>> L2 = [j for j in range(10) if j % 2]

>>> import heapq
>>> [k for k in heapq.merge(L1, L2)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> [k for k in heapq.merge(L1, L2, reverse=True)]
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]

I was expecting [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] because of reverse=True. What am I doing wrong?

1

There are 1 answers

0
yasouser On

Thanks to @Thierry Lathuille's comment. I figured it out. Its a very round about way though.

>>> L1 = [i for i in range(10) if i % 2 == 0]
>>> L2 = [j for j in range(10) if j % 2]
>>> M = [k for k in heapq.merge(sorted(L1, reverse=True), sorted(L2, reverse=True), reverse=True)]
>>> M
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

For merging 2 lists sorted in ascending order but the output should be in descending order, this seems to be much simpler:

>>> sorted(L1 + L2, reverse=True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]