0

I have two tuples with the same rank in a priority queue in python. The get method will take the first element inserted. If two elements have the same priority in the queue, I would like to get the last element inserted returned first :

#python 3.7
import queue
q= queue.PriorityQueue()
q.put((1, 'first_in'))
q.put((1, 'last_in'))
q.put((2, 'not_to_be_returned'))

for i in range(q.qsize()):
    print(q.get(i))

#Returns
(1, 'first_in')
(1, 'last_in')
(2, 'not_to_be_returned')

#looking for : 
(1, 'last_in') # in case of same rank return the last inserted
(1, 'first_in') 
(2, 'not_to_be_returned')

#Merci
greg
  • 3
  • 4
  • I just noticed that 'first_in` was grabbed first because first_in comes first alphabetically. q= queue.PriorityQueue() q.put((1, 'first_in')) q.put((1, 'last_in') q.put((1, 'abcdf') returns (1, 'abcdf'), (1, 'first_in'), (1, 'last_in'). .can we add a second entry – tessie Dec 28 '20 at 14:30
  • @tessie, thank your for your insightful notice. Indeed. – greg Dec 29 '20 at 09:50

2 Answers2

3

If you really need this ordering, the simplest way to solve it is to add a new 2nd element to your tuples that will be used to break ties when the 1st elements in two tuples are the same.

For LIFO ordering you use a counter that you decrement every time you insert. Your elements then become:

q.put((1, 0, 'first_in'))
q.put((1, -1, 'last_in'))
q.put((2, -2, 'not_to_be_returned'))
Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • Exactly right. [This answer](https://stackoverflow.com/questions/54893840/priority-queue-remove-items-with-same-priority-first-one-entered/54916335#54916335) explains why you can't maintain insertion order in a heap-based priority queue, unless you maintain some kind of information about arrival time. – Jim Mischel Jan 20 '21 at 19:54
2

Yep, that would be queue.LifoQueue. See docs.

go2nirvana
  • 1,598
  • 11
  • 20
  • Thanks but lifo queue is no priority queue. l want to return the items with highest priority first , then perform a lifo selection if two items have same priority. – greg Dec 28 '20 at 14:00
  • @greg well, this is not what you've asked in your question. – go2nirvana Dec 28 '20 at 14:01
  • @go2nirvana The title of the question is: "Is there a “Lifo” type priority queue in python?". – ekhumoro Dec 28 '20 at 14:04
  • Sorry I am a newbie, I just changed the code to be more explicit by adding another example. – greg Dec 28 '20 at 14:08