Simple priority queue.
| 399 | |
| 400 | |
| 401 | class PQueue(object): |
| 402 | """Simple priority queue.""" |
| 403 | |
| 404 | def __init__(self, sort_key): |
| 405 | self.sort_key = sort_key |
| 406 | self.contents = [] |
| 407 | self._sorted = False |
| 408 | |
| 409 | def sort(self): |
| 410 | self.contents.sort(key=self.sort_key) |
| 411 | self._sorted = True |
| 412 | |
| 413 | def push(self, o): |
| 414 | self.contents.append(o) |
| 415 | self._sorted = False |
| 416 | |
| 417 | def peek(self, index=None): |
| 418 | if not self._sorted: |
| 419 | self.sort() |
| 420 | if index is None: |
| 421 | index = len(self.contents) - 1 |
| 422 | return self.contents[index] |
| 423 | |
| 424 | def pop(self): |
| 425 | if not self._sorted: |
| 426 | self.sort() |
| 427 | return self.contents.pop() |
| 428 | |
| 429 | def size(self): |
| 430 | return len(self.contents) |
| 431 | |
| 432 | def map(self, f): |
| 433 | return list(map(f, self.contents)) |