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
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.
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.