简体   繁体   中英

Python heapq Priority Queue Maxheap

I understand that priority queues using heapq are implemented as a minheap. I need to make a priority queue implemented as a maxheap that sorts elements by an AWS datetime string. I want elements with the most recent datetime to be popped off of the queue first when I call the heapq.heappop() method. Everything online seems to point towards just using the minheap but making your values negative during input so that greater values are pushed to the top instead of the bottom. However, I can't seem to find any way to actually apply this to a datetime string like this '2021-06-03T16:11:14.206650Z'. Is there a way that I can make that string 'negative' or somehow make it so that more recent dates are popped from the heap first?

There are several ways to approach this.

One is to convert the date/time to an ordinal, and negate that

-dateutil.parser.parse('2021-06-03T16:11:14.206650Z').toordinal()

If you want to retain the original date string, then put this number in a tuple together with the date string.

Convert your timestamps to offsets from a maximum timestamp. Then the most recent timestamps will have the smallest keys, making a minheap appropriate.

Note that dateutil is a third-party module.

>>> import datetime, dateutil
>>> now = datetime.datetime.now().timestamp()
>>> june3 = dateutil.parser.isoparse('2021-06-03T16:11:14.206650Z').timestamp()
>>> june1 = dateutil.parser.isoparse('2021-06-01T00:00:00Z').timestamp()
>>> now - june3 < now - june1
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM