码迷,mamicode.com
首页 > 编程语言 > 详细

Python基本数据结构

时间:2017-10-01 14:25:46      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:range   数据结构   push   while   ide   converter   font   turn   dex   

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基本数据结构

标签:range   数据结构   push   while   ide   converter   font   turn   dex   

原文地址:http://www.cnblogs.com/jasonhaven/p/7617100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!