英文:
What does offer/peek/poll in Java PriorityQueue translate to Python?
问题
我正在尝试在Python中重新实现Java的优先队列(PriorityQueue)数据结构,但是看起来Java的优先队列有一些有趣的方法:
offer(E e)
将指定的元素插入到此优先队列中。peek()
检索但不删除此队列的头部,如果此队列为空,则返回null。poll()
检索并删除此队列的头部,如果此队列为空,则返回null。
这在Python的优先队列中如何翻译?我在Python的版本中没有看到这些方法:https://docs.python.org/3/library/queue.html#queue.PriorityQueue
get()
从队列中移除并返回一个项目。put()
将项目放入队列中。
如果我的理解是正确的:
poll()
==get()
但不确定 offer()
是否与 put()
相同。我们如何重新实现 peek()
?
英文:
I am trying to reimplement Java's PQ in Python data structure, but looks like Java's PQ have some interesting methods:
https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
offer(E e)
Inserts the specified element into this priority queue.peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.poll()
Retrieves and removes the head of this queue, or returns null if this queue is empty.
What does this translate to in Python's PQ? I don't see these methods in Python's version: https://docs.python.org/3/library/queue.html#queue.PriorityQueue
get()
Remove and return an item from the queue.put()
Put item into the queue.
If my understanding is correct:
- poll() == get()
But wasn't sure whether offer() is the same as put()
. And how we have to re-implement peek()
?
答案1
得分: 1
queue
模块专门设计用于线程间通信。其设计不旨在促进单线程使用;例如,诸如 peek
这样的方法在线程同步机制中并没有太多意义,因此 queue.PriorityQueue
不支持 peek
。这与 Go 通道没有查看机制的方式类似。
如果您需要优先队列而不是用于线程间通信的原因,那么 heapq
模块更合适。使用 heapq
,peek
就是 heap[0]
。
英文:
The queue
module is specifically designed for inter-thread communication. Its design is not intended to facilitate single-threaded usage; for example, methods like peek
don't make much sense for a thread synchronization mechanism, so queue.PriorityQueue
doesn't have peek
support. This is similar to how Go channels have no peek mechanism.
If you want a priority queue for reasons other than inter-thread communication, the heapq
module is more appropriate. With heapq
, peek
is just heap[0]
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论