Merge of lazy streams (using generators) in Python

前端 未结 2 1703
旧时难觅i
旧时难觅i 2020-12-22 00:09

I\'m playing with functional capacities of Python 3 and I tried to implement classical algorithm for calculating Hamming numbers. That\'s the numbers which have as prime fac

2条回答
  •  时光说笑
    2020-12-22 00:34

    I will propose this different approach - using Python heapq (min-heapq) with generator (lazy evaluation) (if you don't insist to keep the merge() function)

    from heapq import heappush, heappop
    
    def hamming_numbers(n):
        ans = [1]
    
        last = 0
        count = 0
    
        while count < n:
            x = heappop(ans)
    
            if x > last:
                yield x
    
                last = x
                count += 1
    
                heappush(ans, 2* x)
                heappush(ans, 3* x)
                heappush(ans, 5* x)
    
    
        >>> n  = 20
        >>> print(list(hamming_numbers(20)))
           [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36]
    

提交回复
热议问题