0

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
yasouser
  • 5,113
  • 2
  • 27
  • 41
  • 1
    From the doc: "reverse is a boolean value. If set to True, then the input elements are merged as if each comparison were reversed. To achieve behavior similar to sorted(itertools.chain(*iterables), reverse=True), all iterables must be sorted from largest to smallest." So at each step, merge yields the largest ot the two numbers available at the start of each list. – Thierry Lathuille Oct 14 '20 at 08:16

1 Answers1

0

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]
yasouser
  • 5,113
  • 2
  • 27
  • 41