如何正确使用heap对priorityqueue进行定义和排序?

2024-06-23 02:51:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我的作业是通过让用户以这种格式输入来创建priorityqueue
病例数
案例类型案例ID优先级
以1为最高优先级

Example.
16
I 0 2
I 1 2
D
I 3 3
I 4 1
D
I 6 1
D
I 8 1
D
I 10 2
I 11 1
I 12 3
I 13 2
I 14 3
I 15 2

(我是指正常情况,D是指确定当时的最高优先级),然后按优先级打印剩余的caseID

这是我的密码

import heapq
priority=[]

num=int(input())
for i in range (0,num,1):
    temp=input()
    if (len(temp)>1):
        casetype,caseID,casePrio,=temp.split(" ",2)
        heapq.heappush(priority, (int(caseID),int(casePrio)))
    else:
        heapq.heappop(priority)

for i in range(len(priority)):
    print (priority[i][1]) 

我希望得到这个结果

Output:
11
1
10
13
15
3
12
14

但是换成这个

Output:
11
1
10
15
12
13
14
3


Tags: inforinputoutputlen作业rangetemp
1条回答
网友
1楼 · 发布于 2024-06-23 02:51:43

优先级队列的整体思想是,当您弹出某个内容时,它将为您提供当前在队列中的最高优先级的项目。你不需要自己分类。那只是做额外的工作。你知道吗

如果要按优先级顺序输出队列的其余部分,可以将最终循环替换为:

while (len(priority) > 0)
    print(heapq.heappop(priority));

heappop的每次调用都将返回仍在队列中的最高优先级项。你知道吗

但是,不要指望得到你期望的结果。heapq不保证具有同等优先级的项的删除顺序。例如,如果要按以下顺序插入项目:

10 1
11 2
12 2
13 3

然后删除它们,结果将是10 11 12 13。但如果将插入顺序更改为:

10 1
13 3
11 2
12 2

然后输出将是10 12 11 13。你知道吗

相关问题 更多 >