extracting a heapq in a for loop - there must be more elegant solution
Helmut Jarausch
jarausch at igpm.rwth-aachen.de
Wed Dec 4 04:41:35 EST 2013
On Tue, 03 Dec 2013 15:56:11 +0200, Jussi Piitulainen wrote:
> Helmut Jarausch writes:
> ...
>> I know I could use a while loop but I don't like it.
> ...
>> from heapq import heappush, heappop
>> # heappop raises IndexError if heap is empty
> ...
>> # how to avoid / simplify the following function
>>
>> def in_sequence(H) :
>> try :
>> while True :
>> N= heappop(H)
>> yield N
>> except IndexError :
>> raise StopIteration
>
> That seems equivalent to this:
>
> def in_sequence(H):
> while H: yield heappop(H)
Many thanks, that's something I'd hoped for.
> But I don't like the side-effect. I'd change the name to something
> that indicates the draining of the heap - heapaerobic? - or consider
> sorted(H) instead as others suggested.
Since I fill the heap once and empty it afterwards I regard the side-effect
clearly visible.
Helmut
More information about the Python-list
mailing list