Python數(shù)據(jù)結(jié)構(gòu)知識之棧(二)

一、簡單的Stack的實現(xiàn)和應用:

Stack.py
# Author: Allen Guo
# Data: 2018-01-22
# For github repos please check <https://github.com/wilixx/python_training> .
# For more about the author, see to <www.whoispm.com> but note the disclaimer there.

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)

     def __str__(self): # The modification of __str__()  is for convenience of  "print".
        str = ''
        for item in self.items:
            str=str+item+' '
        return str
Test Code
#------------Note that test goes first-------------------
# Stack_A = Stack()
# Stack_A.push()
# print Stack_A
# Stack_A.isEmpty()
# Stack_A.push('Mathbook')
# Stack_A.push('Chinese')
# Stack_A.push('French')
# Stack_A.push('English')
# Stack_A.push('Foo')
# Stack_A.push('Hello')
# Stack_A.push('Hello')
# Stack_A.push('Hello')
# 
# print Stack_A
# Stack_A.pop()
# print Stack_A
# Stack_A.pop()
# print Stack_A
# Stack_A.pop()
# print Stack_A
# Stack_A.pop()
# print Stack_A
# Stack_A.pop()
# print Stack_A
# Stack_A.pop()
# print Stack_A
# print Stack_A.peek()
# print Stack_A.pop()
# print Stack_A.peek()
# print Stack_A.pop()
# print Stack_A.peek()
# print Stack_A.pop()
# print Stack_A.peek()
# print Stack_A.pop()
# print Stack_A.peek()

二、利用Stack檢查括號:

ParChecker.py
# Author: Allen Guo
# Data: 2018-01-22
# For github repos please check <https://github.com/wilixx/python_training> .
# For more about the author, see to <www.whoispm.com> but note the disclaimer there.

from Stack import Stack
def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol)
        elif symbol == ")":
            s.pop()
        elif symbol == ")":
            pass
        index = index + 1
    if balanced and s.isEmpty():
        return True
    else:
        return False
print(parChecker('(((A)B))'))
print(parChecker('(()'))

三、解析數(shù)學表達式:(未完待續(xù))

# Author: Allen Guo
# Data: 2018-01-22
# For github repos please check <https://github.com/wilixx/python_training> .
# For more about the author, see to <www.whoispm.com> but note the disclaimer there.

# There is still not very well. Waiting for when I am free...
from 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 in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or 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 " ".join(postfixList)

print(infixToPostfix("A * B + C * D"))
print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )"))

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容