Internal working of python heapq merge. How does it sort a list without generating the list

后端 未结 2 968
遥遥无期
遥遥无期 2021-01-05 18:37

How does heapq.merge() sort a list even without generate the list?

Not sure if I stated clear.
So, this is raised from the Super Ugly Number proble

相关标签:
2条回答
  • 2021-01-05 18:51

    It takes n already sorted iterables. It can then look at the smallest value in each of those and use that. The smallest one is always the first item, then the second item, then the third item, since they are each sorted.

    0 讨论(0)
  • 2021-01-05 19:15

    The implementation of heapq.merge is pure Python, you can read its code directly if you want.

    As you might guess from the module it's implemented in, it uses a heap to merge the iterables it's passed. If the iterables (generators in this case) each yield their values in order, it will combine them so that the values it yields are also in order. It doesn't eliminate duplicate values, which is why the code you show checks to see if the latest value is equal to the previous one.

    0 讨论(0)
提交回复
热议问题