python学习3--python复杂数据类型

栏目: Python · 发布时间: 8年前

内容简介:python学习3--python复杂数据类型

1 堆

堆是一种二叉树,其中每个父节点的值都小于或等于其所有子节点的值,最小的元素总是位于二叉树的根节点。

堆的创建

import heapq
import random
data = range(10)
random.shuffle(data) #打乱顺序
heap = []
 for n in data:
     heapq.heappush(heap,n)
 print heap

heapq.heappushpop(heap,0.5) #新数据入堆
heapq.heappop(heap) #弹出最小的元素,堆重建

列表转化为堆

myheap = [100,2,3,4,22,7,10,5]
heapq.heapify(myheap) #将列表转化为堆
heapq.heapreplace(myheap,6) #替代堆栈元素值,堆重建
heapq.nlargest(3,myheap) #返回最大的3个值
heapq.nsmallest(3,myheap) #最小3个

2 队列

队列的特点是First in first out, last in last out,先进先出,后进后出

import Queue
q = Queue.Queue()
 q.put(0) #元素入队
q.put(1)
 q.put(2)
 print q.queue #deque([0, 1, 2])
 print q.get() #元素0先出队
print q.queue() #deque([1, 2])

3 栈

栈的特点是Last in last out,first in last out,后进先出,先进后出

list 就可以实现栈的基本操作,append()相当于入栈,pop()相当于出栈,但是当列表为空时pop()操作会有异常,也无法限制栈的大小。

import Stack
x = Stack.Stack()
x.push(1)
x. push(2)
x.show()
x.pop()
x.show()
class Stack:
     def __init__(self, size=10):
         self._content = []
         self._size = size
     def empty(self):
         self._content = []
     def isEmpty(self):
         if not self._content:
             return True
         else:
             return False
     def setSize(self,size):
         self._size = size
     def isFull(self):
         if len(self._content)==self._size:
             return True
         else:
             return False
     def push(self,v):
         if len(self._content)<self._size:
             self._content.append(v)
         else:
             print 'Stack Full'
     def pop(self):
         if self._content:
             return self._content.pop()
         else:
             print 'Stack is empty!'
     def show(self):
         print self._content
     def showRemainderSpace(self):
         print 'Stack can still PUSH',self.size-len(self._content),'elements.'
     if __name__=='__main__':
         print 'Please use me as a module'

4 链表

可以直接使用list及其基本操作实现链表的功能

linkTable = []
linkTable.append(3)
linkTable.append(5)
linkTable.insert(1,4)
linkTable.remove(linkTable[1])

5 二叉树

6 有向图


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Convergence Culture

Convergence Culture

Henry Jenkins / NYU Press / 2006-08-01 / USD 30.00

"Convergence Culture" maps a new territory: where old and new media intersect, where grassroots and corporate media collide, where the power of the media producer, and the power of the consumer intera......一起来看看 《Convergence Culture》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码