[Python-Dev] Re: heapq API
Scott David Daniels
Scott.Daniels at Acm.Org
Fri Jun 18 03:13:15 EDT 2004
> Josiah Carlson wrote:
> Scott David Daniels wrote:
>> Raymond Hettinger wrote:
>>> if not heap or item < heap[0]:
>>> return item
>>> return heapreplace(heap, item)
>> Better is:
>> if heap and heap[0] < item:
>> return heapreplace(heap, item)
>> return item
> The or method short-circuits too....
Sorry, I was (inadvertently) being cryptic:
I was avoiding the heapreplace call if item == heap[0].
Since "<" is the native ordering comparison, I reordered
the comparison to continue using "<".
While I was rearranging I dropped the "not" which was
probably a useless micro-optimization, but I usually
avoid not for clarity for myself these days. I wouldn't
presume to correct just to fiddle out the not.
For the list, I'd probably have done better simply to write:
> ...
> Better is:
> if not heap or item <= heap[0]:
> return item
> return heapreplace(heap, item)
> because you want to avoid calling heapreplace if possible.
--
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-Dev
mailing list