0

As shown in a basic example in the doc, one can always use a tuple so that the first element is compared as the priority key. However, what if the associated data are not comparable? What would be an elegant way to resolve this?

For example,

import heapq
h = [(3, 2), (4, 3)]
heapq.heapify(h)
heapq.heappush(h, (3, (0, 1)))

This emits

TypeError: unorderable types: tuple() < int()
xuhdev
  • 8,018
  • 2
  • 41
  • 69
  • Do what the example does: put a unique count into the tuple after the priority, so that the data items themselves will never need to be compared. – PM 2Ring Sep 14 '18 at 09:41
  • @PM2Ring The uniqueness cannot be guaranteed. – xuhdev Sep 14 '18 at 18:28
  • Why not? Create a simple generator (eg use itertools.count), and whenever you create a tuple to put on the heap call that generator to get a new number. – PM 2Ring Sep 14 '18 at 18:34
  • @PM2Ring Sorry I misunderstood you. Your solution would work, but I'm seeking for a more elegant solution. – xuhdev Sep 14 '18 at 19:13
  • It looks elegant enough to me. ;) And it's essentially the same strategy that `heapq.merge` uses, as you can see in [the source](https://github.com/python/cpython/blob/b2ecb8b486d85d11ee7b523dfd2c76b2820bbe83/Lib/heapq.py#L314). – PM 2Ring Sep 14 '18 at 19:39
  • @PM2Ring OK.. I guess that's the best way to do. Thanks anyway. – xuhdev Sep 14 '18 at 19:45

0 Answers0