python入门:关于堆操作的一个模块heapq及其函数
2018-04-08 22:14
603 查看
若有帮助到你,记得点赞u。
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 20:25:02 2018
@author: Lelouch_C.C
"""
#python中没有独立的对类型,只有一个包含一些堆操作函数的模块heapq,q指queue队列
from heapq import *
from random import shuffle
data=list(range(10))
shuffle(data) #shuffle英文意思是洗牌,这里进行随机打乱data中元素顺序
heap=[]
for n in data:
heappush(heap,n) #将n入堆
print(heap)
#输出:[0, 1, 2, 4, 6, 9, 3, 7, 5, 8],输出结果可能不同
heappush(heap,0.5)
print(heap)
#输出:[0, 0.5, 2, 4, 1, 9, 3, 7, 5, 8, 6],输出结果可能不同
"""
上述排序并不严格,但也并不随意.
遵循堆属性:i位置处的元素总比2i和2i+1位置处的元素小.
注意:i从1开始.
"""
heappop(heap)
#heappop会弹出最小元素,一般来说都是在索引0处,
#并且在保证堆属性的条件下,会将剩余的元素中最小的那个占据索引0的位置
print(heap)
#输出:[0.5, 1, 6, 2, 5, 8, 7, 4, 3, 9],输出结果可能不同
heappop(heap)
print(heap)
#输出:[1, 3, 2, 4, 5, 9, 6, 8, 7],输出结果可能不同
heap1=[5,8,4,6,1,7,9,3,2]
heapify(heap)
#heapify将任意的列表作为参数,并通过尽可能少的操作使得列表满足堆属性。
#注意:对于任意的列表,不能直接用heappush、heappop、heapreplace等,必须先用heapify进行合法化
print(heap)
#输出:[1, 2, 5, 3, 4, 7, 8, 6, 9]
heapreplace(heap,0.5)
#heapreplace会弹出最小元素,并将新元素推入,返回被推出的最小值
print(heap)
#输出:[0.5, 2, 6, 4, 3, 7, 8, 9, 5]
若有帮助到你,记得点赞u。
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 20:25:02 2018
@author: Lelouch_C.C
"""
#python中没有独立的对类型,只有一个包含一些堆操作函数的模块heapq,q指queue队列
from heapq import *
from random import shuffle
data=list(range(10))
shuffle(data) #shuffle英文意思是洗牌,这里进行随机打乱data中元素顺序
heap=[]
for n in data:
heappush(heap,n) #将n入堆
print(heap)
#输出:[0, 1, 2, 4, 6, 9, 3, 7, 5, 8],输出结果可能不同
heappush(heap,0.5)
print(heap)
#输出:[0, 0.5, 2, 4, 1, 9, 3, 7, 5, 8, 6],输出结果可能不同
"""
上述排序并不严格,但也并不随意.
遵循堆属性:i位置处的元素总比2i和2i+1位置处的元素小.
注意:i从1开始.
"""
heappop(heap)
#heappop会弹出最小元素,一般来说都是在索引0处,
#并且在保证堆属性的条件下,会将剩余的元素中最小的那个占据索引0的位置
print(heap)
#输出:[0.5, 1, 6, 2, 5, 8, 7, 4, 3, 9],输出结果可能不同
heappop(heap)
print(heap)
#输出:[1, 3, 2, 4, 5, 9, 6, 8, 7],输出结果可能不同
heap1=[5,8,4,6,1,7,9,3,2]
heapify(heap)
#heapify将任意的列表作为参数,并通过尽可能少的操作使得列表满足堆属性。
#注意:对于任意的列表,不能直接用heappush、heappop、heapreplace等,必须先用heapify进行合法化
print(heap)
#输出:[1, 2, 5, 3, 4, 7, 8, 6, 9]
heapreplace(heap,0.5)
#heapreplace会弹出最小元素,并将新元素推入,返回被推出的最小值
print(heap)
#输出:[0.5, 2, 6, 4, 3, 7, 8, 9, 5]
相关文章推荐
- python 关于自定义 模块(类,函数),包的导入
- Python 关于集合的方法函数和相关模块(利于做排重)
- think python学习心得-(1)关于函数和模块
- Python 第三篇(上):python文件基础操作、json模块、lambda、map、filter、reduce和函数位置参数
- Python的shutil模块中文件的复制操作函数详解
- python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块
- WinSocket套接字关于Connect函数通过GetLastError 返回10038或者(在一个非套接字上尝试了一个操作)
- 基础入门_Python-模块和包.为wsgiref实现的WSGI服务器编写处理函数?
- Python3基础 创建一个模块 导入并调用其中的函数 主代码与模块代码在同一文件夹下
- 好吧我承认最近一直入门python! 关于python3 和 python2 List 的一点区别 以及python 通过enumerate 内建函数遍历List
- 函数知识及文件IO操作(python快速入门精华切记03)
- python写的模块:财务管理中关于时间价值的函数
- 基础入门_Python-模块和包.运维开发中MySQLdb CRUD操作的最佳实践?
- Python的shutil模块中文件的复制操作函数详解
- js中关于map的增、删、改、查操作及其js中如何建立一个对象
- 基础入门_Python-模块和包.深入SQLAlchemy之玩转各种增删查改操作?
- Python OS 文件操作模块常用函数
- Python中shutil模块的常用文件操作函数用法示例
- [转]几个python 入门程序--例2( 如何将多个模块打包成一个模块)
- python基础:os模块中关于文件/目录常用的函数使用方法