第八章总结

8.5. heapq — 堆队列算法

有8个算法

方法
heappush
heappop
heappushpop
heapreplace
heapify
merge
nlargest
nsmallest
  • 最小堆封装
# 最小堆封装
from heapq import *
import pprint
class MinHeap:
def __init__(self, iterable):
self._iteralbe = []
self._max = 1000
self.linearpush(iterable)
# 添加
def push(self, item):
heappush(self._iteralbe, item)
# 弹出
def pop(self):
res = None
try:
res = heappop(self._iteralbe)
except Exception as e:
pprint.pprint(e)
return res
# 一个组合动作,先添加后弹出
def pushpop(self, item):
res = None
try:
res = heappushpop(self._iteralbe, item)
except Exception as e:
pprint.pprint(e)
return res
# 一个组合动作,先弹出再添加
def replace(self, item):
res = None
try:
res = heapreplace(self._iteralbe, item)
except Exception as e:
pprint.pprint(e)
return res
# 线性将列表加入到堆中,并且将原来的列表设置成堆
def linearpush(self, iterable):
for it in iterable:
self._iteralbe.append(it)
heapify(self._iteralbe)
# 将所有列表合并到堆中
def mergeAll(self, *iterables):
arrs = [sorted(x) for x in iterables]
arrs.append(self._iteralbe)
self._iteralbe = list(merge(*tuple(arrs)))
# 返回n个最大值
def nlagrge(self, n):
if n == 1:
return max(self._iteralbe)
l = len(self._iteralbe)
if l != 0:
if l < self._max:
return nlargest(n, self._iteralbe)
else:
return sorted(self._iteralbe, reversed=True)[:n]
return None
# 返回n个最小值
def nsmall(self, n):
if n == 1:
return self.getMin()
l = len(self._iteralbe)
if l != 0:
if l < self._max:
return nsmallest(n, self._iteralbe)
else:
return sorted(self._iteralbe)[:n]
return None
# 返回最小值
def getMin(self):
if len(self._iteralbe) == 0:
return None
else:
return self._iteralbe[0]
a = [10, 2, 9, 4, 3, 5, 8, 6, 7, 1]
heap = MinHeap(a)
print("最小值是 {0}".format(heap.getMin()))
print("先添加后弹出是 {0}".format(heap.pushpop(0)))
print("先弹出后添加是 {0}".format(heap.replace(0)))
print("最小值是 {0}".format(heap.pop()))
print("前20个最大值是 {0}".format(heap.nlagrge(20)))
print("前2个最小值是 {0}".format(heap.nsmall(2)))
heap.mergeAll([8, 2, 4], [9, 10, -1])
print("合并之后的最小值是 {0}".format(heap.getMin()))

执行后的效果如下:

  • 实现优先队列
# 优先队列封装
import itertools
class priority_deque:
def __init__(self):
self.deque = []
self.entry_findeer = {}
self.conter = itertools.count() # 用来处理优先级相同的任务
def add_task(self, task, priority= 0):
if task in self.entry_findeer:
self.remove_task(task)
count = next(self.conter)
entry = [priority, count, task]
self.entry_findeer[task] = entry
heappush(self.deque, entry)
def remove_task(self, task):
if task in self.entry_findeer:
self.entry_findeer.pop(task)
def pop_task(self):
while self.deque:
return heappop(self.deque)
deque = priority_deque()
deque.add_task("第一个任务")
deque.add_task("第二个任务")
print(deque.pop_task())
print(deque.pop_task())

8.6.bisect — 数组分割算法

有6个函数

函数
biset_left
biset_right/biset
insort_left
insort_right/insort

实现

import bisect
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect.bisect_left(a, x)
if i:
return a[i-1]
raise ValueError
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect.bisect_right(a, x)
if i:
return a[i-1]
raise ValueError
def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect.bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError
def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect.bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError

8.7. array - 高效的数值数组

参见列表

常用的函数包括:

函数 描述
array
itemsize
append
count
extend(iterable)
index(x)
insert(i, x)
pop([i])
remove(x)
reverse()
tolist()
tobytes()
tounicode()

8.8. weakref - 弱参考

弱引用的主要用途是实现持有大对象的高速缓存或映射,其中希望大对象不会因为它出现在高速缓存或映射中而保持活着。

8.9. types - 内建类型的动态类型创建和名称

动态创建新类型

import types
# Methods
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
def cost(self):
return self.shares * self.price
cls_dict = {
'__init__' : __init__,
'cost' : cost,
}
Stock = types.new_class('Stock', (), {}, lambda ns: ns.update(cls_dict))
Stock.__module__ = __name__
s = Stock('ACME', 50, 91.1)
print(s.cost())

注意

__module__属性代表着是从哪个模块导入进行来的,向上面那样设置以后,Stock.__module__就变成__main__

参考文章

8.10. copy - 浅和深复制操作

  • copy:浅拷贝
  • deepcopy:深拷贝
  • copy.error:引发模块特定错误。

注意两者的区别,区别在于所拷贝对象里面是否还有比较复杂的数据结构,否则两者是一样。

8.11. pprint - 数据漂亮打印机

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False)

如果 stream 为 None,使用 sys.stdout,indent为缩进,width为宽度,depth为深度。

Python 第八章笔记的更多相关文章

  1. 【原】Learning Spark (Python版) 学习笔记(三)----工作原理、调优与Spark SQL

    周末的任务是更新Learning Spark系列第三篇,以为自己写不完了,但为了改正拖延症,还是得完成给自己定的任务啊 = =.这三章主要讲Spark的运行过程(本地+集群),性能调优以及Spark ...

  2. 《简明python教程》笔记一

    读<简明Python教程>笔记: 本书的官方网站是www.byteofpython.info  安装就不说了,网上很多,这里就记录下我在安装时的问题,首先到python官网下载,选好安装路 ...

  3. python 正则使用笔记

    python正则使用笔记 def remove_br(content): """去除两边换行符""" content = content.r ...

  4. python核心编程--笔记

    python核心编程--笔记 的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找pyt ...

  5. python 库安装笔记

    python 库安装笔记 zoerywzhou@163.com http://www.cnblogs.com/swje/ 作者:Zhouwan 2017-2-22 友情提示 安装python库的过程中 ...

  6. Python Click 学习笔记(转)

    原文链接:Python Click 学习笔记 Click 是 Flask 的团队 pallets 开发的优秀开源项目,它为命令行工具的开发封装了大量方法,使开发者只需要专注于功能实现.恰好我最近在开发 ...

  7. Python源代码剖析笔记3-Python运行原理初探

    Python源代码剖析笔记3-Python执行原理初探 本文简书地址:http://www.jianshu.com/p/03af86845c95 之前写了几篇源代码剖析笔记,然而慢慢觉得没有从一个宏观 ...

  8. C#语言和SQL Server第八章笔记

    一:                                                                                                   ...

  9. Python网络爬虫笔记(五):下载、分析京东P20销售数据

    (一)  分析网页 下载下面这个链接的销售数据 https://item.jd.com/6733026.html#comment 1.      翻页的时候,谷歌F12的Network页签可以看到下面 ...

随机推荐

  1. 完全背包hdu1114

    https://vjudge.net/contest/68966#problem/F 初始化就行了:dp[0]=0: 这题还要刚好装满背包,输出时进行判断 #include<map> #i ...

  2. 安卓OKhttp请求封装

    目前安卓开发中使用的网络工具为OKhttp,但是okhttp的使用还不是很方便,在okhttp的基础上再对请求进行封装会极大的方便网络调用. 下面直接上代码. 请求封装 public class Ht ...

  3. JDK安装、java环境配置

    JDK是Java语言的软件开发工具包,主要用于移动设备.嵌入式设备上的java应用程序.JDK是整个java开发的核心,它包含了JAVA的运行环境,JAVA工具和JAVA基础的类库. JRE(Java ...

  4. 0基础搭建Hadoop大数据处理-环境

    由于Hadoop需要运行在Linux环境中,而且是分布式的,因此个人学习只能装虚拟机,本文都以VMware Workstation为准,安装CentOS7,具体的安装此处不作过多介绍,只作需要用到的知 ...

  5. springboot(三):Spring boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

  6. Intellij Shortcuts

    ctrl+shift+F : search in whole project ctrl+hover : check the field info in brief ctrl+Q : check the ...

  7. 基于java:读写一个英文的txt文件,记录单词个数,并输出十个出现最多的单词及出现的个数;

    import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; class W ...

  8. 1.Java 加解密技术系列之 BASE64

    Java 加解密技术系列之 BASE64 序号 背景 正文 总结 序 这段时间,工作中 用到了 Java 的加解密技术,本着学习的态度,打算从这篇文章开始,详细的研究一番 Java 在加解密技术上有什 ...

  9. [原创]首次SDN比赛的记录-部分

    SDN大赛环境搭建和第一大题实现 由于物理设备不足的原因,故用虚拟机实现Floodlight控制器,openvswitch(以下简称:OVS)和mininet各种要用到的SDN环境的搭建.下面将给出它 ...

  10. SVN版本控制系统搭建(+结合http服务)

    .zise { background: #CCCCFF; color: white; text-align: center } .fense { color: #FFCCCC; text-align: ...