栈(Stack)的python实现及应用

来源:互联网 发布:java tomcat绝对路径 编辑:程序博客网 时间:2024/06/01 09:56

栈的说明

  • 栈是一个线性的数据结构
  • 栈遵循LIFO的原则,Last In First Out , 即后进先出
  • 栈顶为top,栈底为base

栈的函数列表

代码实现

# author: HuYong# coding=utf-8class 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[-1]    def size(self):        return len(self.items)

测试如下:

In[2]: from Stack import StackIn[3]: s = Stack()In[4]: s.isEmpty()Out[4]: TrueIn[5]: s.push(4)In[6]: s.peek()Out[6]: 4In[7]: s.push("Dog")In[8]: s.pop()In[10]: s.peek()Out[10]: 4In[11]: s.size()Out[11]: 1

应用

字符串反转

def reverseTheString(s):    stack = Stack()    for each in s:        stack.push(each)    result = ''    while not stack.isEmpty():        result += stack.pop()    return result

简单的括号匹配

def parChecker(symbolString):    s = Stack()    balanced = True    index = 0    while index < len(symbolString) and balanced:        symbol = symbolString[index]        if symbol == "(":            s.push(symbol)        else:            if s.isEmpty():                balanced = False            else:                s.pop()        index = index + 1    if balanced and s.isEmpty():        return True    else:        return False

一般的括号匹配

def parChecker(symbolString):    stack = Stack()    balance = True    index = 0    while balance and index < len(symbolString):        symbol = symbolString[index]        if symbol in "([{":            stack.push(symbol)        else:            if stack.isEmpty():                balance = False            else:                top = stack.pop()                balance = match(top,symbol)        index = index + 1    if balance and  stack.isEmpty():        return True    else:        return Falsedef match(open,close):    opens = "([{"    closes = ")]}"    return opens.index(open) == closes.index(close)

十进制转化为任意进制

def baseConverter(decNumber,base):    digits = "0123456789ABCDEF"    stack = Stack()    result = ""    while decNumber != 0:        num = decNumber % base        stack.push(digits[num])        decNumber = decNumber/base    while not stack.isEmpty():        result = result + stack.pop()    return result

计算一般数学表达式

  • 先转变为后序表达再计算
def infixToPostfix(infixexpretion):    prec = {}    prec["*"] = 3    prec["/"] = 3    prec["+"] = 2    prec["-"] = 2    prec["("] = 1    opStack = Stack()    postfixList = []    tokenList = list(infixexpretion)    for token in tokenList:        if token  in "0123456789":            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 postfixListdef calculate(first , second , token):    if token == '+':        result = first + second    elif token == '-':        result = first - second    elif token == '*':        result = first * second    elif token == '/':        result = first / second    return resultdef calculatePostfix(PostfixList):    numberStack = Stack()    for token in PostfixList:        if token in "0123456789":            numberStack.push(float(token))        else:            second = numberStack.pop()            first = numberStack.pop()            result = calculate(first,second,token)            numberStack.push(result)    return resultprint calculatePostfix(infixToPostfix("3*(2+3)")) #15.0
0 0
原创粉丝点击