Rewrite _HeapDict.pop() a bit

This commit is contained in:
Petr Viktorin 2011-04-27 14:50:07 +03:00
parent e4c0d0b16b
commit b27187e99a

View file

@ -775,7 +775,11 @@ def a_star(initial, expand, is_goal, estimate=lambda x: 0, notify=None,
opened[initial] = (est, 0, est) opened[initial] = (est, 0, est)
came_from = {initial: None} # node -> (prev_node, came_from[prev_node]) came_from = {initial: None} # node -> (prev_node, came_from[prev_node])
while True: # _HeapDict will raise StopIteration for us while True: # _HeapDict will raise StopIteration for us
try:
x, (f, g, h) = opened.pop() x, (f, g, h) = opened.pop()
except IndexError:
raise StopIteration
closed.add(x) closed.add(x)
if notify is not None: if notify is not None:
@ -837,20 +841,13 @@ class _HeapDict(object):
def pop(self): def pop(self):
"""Return (key, value) with the smallest value. """Return (key, value) with the smallest value.
Raise StopIteration (!!) if empty Raises IndexError if empty
""" """
while True: while True:
try: value, key = heapq.heappop(self.heap) # raises IndexError for us
value, key = heapq.heappop(self.heap) if key in self.dict:
if value is self.dict[key]:
del self.dict[key] del self.dict[key]
return key, value return key, value
except KeyError:
# deleted from dict = not here
pass
except IndexError:
# nothing more to pop
raise StopIteration
### ###
### Result objects ### Result objects