Python基本数据结构
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基本数据结构相关的知识,希望对你有一定的参考价值。
栈
class Stack: def __init__(self): self.items = []
def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items)
队列
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
双端队列
class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self, item):
self.items.append(item)
def addRear(self, item):
self.items.insert(0,item)
def removeFront(self):
return self.items.pop()
def removeRear(self):
return self.items.pop(0)
def size(self):
return len(self.items)
应用
括号匹配:
def check(s):
lefts = [‘(‘, ‘[‘, ‘{‘]
rights = [‘)‘, ‘]‘, ‘}‘]
stack = Stack()
for c in s:
if c in lefts:
stack.push(c)
else:
if stack.is_empty():
return False
c_pop = stack.pop()
if lefts.index(c_pop) != rights.index(c):
return False
if stack.is_empty:
return True
return False
进制转换
def divideBy2(decNumber):
reback = Stack()
while (decNumber > 0):
reback.push(decNumber % 2)
decNumber = decNumber // 2
binstr = ‘‘
while not reback.is_empty():
binstr = binstr + str(reback.pop())
return binstr
def baseConverter(decNumber, base):
‘‘‘
将十进制数字转成任意进制数字
‘‘‘
digits = ‘0123456789ABCDEF‘
reback = Stack()
while (decNumber > 0):
reback.push(decNumber % base)
decNumber = decNumber // base
basestr = ‘‘
while not reback.is_empty():
basestr = basestr + digits[reback.pop()]
return basestr
两个栈实现队列
# coding:utf-8
from pythonds.basic.stack import Stack
class StacToQueue(object):
def __init__(self):
self.stack_one = Stack()
self.stack_two = Stack()
def push(self, item):
self.stack_one.push(item)
def pop(self):
if self.stack_two.isEmpty():
while not self.stack_one.isEmpty():
self.stack_two.push(self.stack_one.pop())
return self.stack_two.pop()
def size(self):
return len(self.stack_one) + len(self.stack_two)
def isEmpty(self):
return self.size() == 0
if __name__ == ‘__main__‘:
queue = StacToQueue()
for x in range(5):
queue.push(x)
for x in range(5):
print(queue.pop())
以上是关于Python基本数据结构的主要内容,如果未能解决你的问题,请参考以下文章
Python练习册 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-),(http://tieba.baidu.com/p/2166231880)(代码片段