Dongxing's Wiki Dongxing's Wiki
首页
  • 剑指 Offer
  • LeetCode
  • 算法与数据结构
  • Python 语言
  • Web 开发
  • Hive
  • Elastic Search
  • 机器学习
  • NLP
  • 检索技术
  • 数据分析
  • 经验笔记
  • Linux 配置
  • 博客进化记
  • 杂谈
GitHub (opens new window)
首页
  • 剑指 Offer
  • LeetCode
  • 算法与数据结构
  • Python 语言
  • Web 开发
  • Hive
  • Elastic Search
  • 机器学习
  • NLP
  • 检索技术
  • 数据分析
  • 经验笔记
  • Linux 配置
  • 博客进化记
  • 杂谈
GitHub (opens new window)
  • 语法

    • conda常用命令整理
    • Python、Django 中使用 logging 便捷处理日志记录
    • Python 中的 is 和 ==
    • Python 中的堆和优先队列
  • Web

    • 使用django快速搭建微信公众号后台服务
    • Django 常用操作笔记
    • 使用haystack实现django全文检索搜索引擎功能
    • django session何时被修改
  • Python
  • 语法
anthony
2019-08-04

Python 中的堆和优先队列

以 leetcode 23题为例说明一下python中堆和优先队列的用法。

Python 2 用法

from Queue import PriorityQueue  # python2中的包,Queue大写首字母

class Solution:
    def mergeKLists(self, lists):
        head = point = ListNode(-1)
        q = PriorityQueue()
        for l in lists:
            if l:
                q.put((l.val, l))  # put进去tuple,第一个是用于比较的值,第二个是存的信息
        while not q.empty():  # empty判空
            val, node = q.get()  # get获取最小元素
            point.next = node
            point = point.next
            node = node.next
            if node:
                q.put((node.val, node))
        return head.next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Python 3的不同点:

 
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
from queue import PriorityQueue  # 注意,3中这里变成了小写

class Solution:
    def mergeKLists(self, lists):
        head = point = ListNode(-1)
        q = PriorityQueue()
        for l in lists:
            if l:
				# 要注意这里!py3中要求put进去的元素l必须是可比较大小的,当第一个元素val相同时将根据第二个元素l的大小来比较。所以或者给ListNode类重写 eq 和 lt 函数使之变成可比较的,或者人工加一个例如id作为第二个元素来规避此问题
                q.put((l.val, id(l), l))
        while not q.empty():
            val, _, node = q.get()
            point.next = node
            point = point.next
            node = node.next
            if node:
                q.put((node.val, id(node), node))
        return head.next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

PriorityQueue 其实是 heapq 做了一点简单封装,因此可以自己用heapq来做:

import heapq

class MyPriorityQueue:

    def __init__(self):
        self._index = 0
        self.queue = []

    def push(self, priority, val):
        heapq.heappush(self.queue, (priority, self._index, val))
        self._index += 1

    def pop(self):
        return heapq.heappop(self.queue)[-1]
		
	def get_top(self):
		return heapq.nsmallest(1, self.queue)[0][-1]
		
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
上次更新: 2020/09/19, 22:09:00
Python 中的 is 和 ==
使用django快速搭建微信公众号后台服务

← Python 中的 is 和 == 使用django快速搭建微信公众号后台服务→

Theme by Vdoing | Copyright © 2017-2023 anthony 京ICP备17072417-3
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式