栈
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 enqueue(self, item):
self.stack_one.push(item)
def dequeue(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
class Dequeue(object):
def __init__(self):
self.items = []
def enqueueFront(self, item):
self.items.insert(0, item)
def dequeueRear(self):
return self.items.pop()
def enqueueRear(self, item):
self.items.append(item)
def dequeueFront(self):
return self.items.pop(0)
def size(self):
return len(self.items)
def isEMpty(self):
return self.items == []
if __name__ == '__main__':
queue = StacToQueue()
for x in range(5):
queue.enqueue(x)
for x in range(5):
print(queue.dequeue())
回文判断
def palchecker(string):
chardequeue = Dequeue()
for ch in string:
chardequeue.enqueueFront(ch)
while not chardequeue.isEMpty():
front = chardequeue.dequeueFront()
rear = chardequeue.dequeueRear()
if front != rear:
return False
return True
if __name__ == '__main__':
print(palchecker("123321"))
print(palchecker("124561"))
中缀表达式转前缀表达式或者后缀表达式
# coding:utf-8
from pythonds.basic.stack import Stack
def infixToPostfix(infixexpr):
# 记录优先级
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
# 操作符栈
opStack = Stack()
# 后缀
postfixList = []
# 单词列表
tokenList = infixexpr.split(' ')
for token in tokenList:
if token.isdigit(): # 分词部分纯数字
postfixList.append(token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return "".join(postfixList)
def infixToPrefix(infixexpr):
# 记录优先级
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
# 操作符栈
opStack = Stack()
# 后缀
prefixList = []
# 单词列表
tokenList = infixexpr.split(' ')
for token in tokenList:
if token.isdigit():
prefixList.insert(0, token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
prefixList.insert(0, topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
prefixList.insert(0, opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
prefixList.insert(0, opStack.pop())
return "".join(prefixList)
def caculatePostfix(postfixexp):
numbers = "0123456789"
tokenList = postfixexp.split(' ')
numStack = Stack()
for token in tokenList:
if token in numbers:
numStack.push(int(token))
else:
numb = numStack.pop()
numa = numStack.pop()
result = doMath(numa, numb, token)
numStack.push(result)
return numStack.pop()
def doMath(a, b, op):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
if __name__ == '__main__':
postList = infixToPostfix("1 + 3 * 5 / ( 6 - 4 )")
print(postList)
pretList = infixToPrefix("1 + 3 * 5 / ( 6 - 4 )")
print(pretList)
print(caculatePostfix(" ".join(postList)))#对于个位数字运算可以直接加空格,对于多位数字需要在转为后缀字符串时操作