# Python3.5 # å®ä¹ä¸ä¸ªæ ç±» class Stack(): # æ çåå§å def __init__(self): self.items = [] # å¤ææ æ¯å¦ä¸ºç©º,为空è¿åTrue 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) # æ 屿§æµè¯ # æµè¯æ°æ® # s = Stack() # print(s.isEmpty()) # s.push(4) # s.push('dog') # print(s.peek()) # s.push(True) # print(s.isEmpty()) # s.push(8.4) # print(s.pop()) # print(s.pop()) # print(s.size()) # å©ç¨æ å°å串çå符å转 def revstring(mystr): # your code here s = Stack() outputStr = '' for c in mystr: s.push(c) while not s.isEmpty(): outputStr += s.pop() return outputStr # print(revstring('apple')) # print(revstring('x')) # print(revstring('1234567890')) # å©ç¨æ 夿æ¬å·å¹³è¡¡Balanced parentheses def parChecker(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol in '([{': s.push(symbol) else: if s.isEmpty(): balanced = False else: top = s.pop() if not matches(top, symbol): balanced = False index += 1 if balanced and s.isEmpty(): return True else: return False def matches(open, close): opens = '([{' closers = ')]}' return opens.index(open) == closers.index(close) # print(parChecker('({([()])}){}')) # å©ç¨æ å°åè¿å¶æ´æ°è½¬å为äºè¿å¶æ´æ° def Dec2Bin(decNumber): s = Stack() while decNumber > 0: temp = decNumber % 2 s.push(temp) decNumber = decNumber // 2 binString = '' while not s.isEmpty(): binString += str(s.pop()) return binString # print(Dec2Bin(42)) # å©ç¨æ å®ç°å¤è¿å¶è½¬æ¢ def baseConverter(decNumber, base): digits = '0123456789ABCDEF' s = Stack() while decNumber > 0: temp = decNumber % base s.push(temp) decNumber = decNumber // base newString = '' while not s.isEmpty(): newString = newString + digits[s.pop()] return newString # print(baseConverter(59, 16)) # å©ç¨æ å®ç°æ®éå¤é¡¹å¼çåç¼è¡¨è¾¾å¼ 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 )"))