def infixToPostfix(infixexpr): opstack = Stack() # 创建空栈 result = [] # 结果的列表 prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1} # 运算符的优先级 operator_list = ['+', '-', '*', '/'] for token in tolist(infixexpr): if token.capitalize() in string.ascii_uppercase: # 判断是否是操作数 result.append(token.capitalize()) else: if token == '(': # 判断是是否是左括号 opstack.push(token) elif token == ')': # 判断是否是右括号 topToken = opstack.pop() while topToken != '(': result.append(topToken) topToken = opstack.pop() elif token in operator_list: # 判断是否是运算符 while not opstack.isEmpty() and (prec[opstack.peek()] >= prec[token]): result.append(opstack.pop()) opstack.push(token) else: pass while not opstack.isEmpty(): result.append(opstack.pop()) return "".join(result)
def parChecker(symbolString): """ 简单括号是否匹配 :param symbolString: 括号字符串 :return: bool型,匹配:True,不匹配:False """ # 初始化一个栈 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 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)
def reverse_string(stack: Stack, input_str: str): for char in input_str: stack.push(char) rev_str = "" while not stack.is_empty(): rev_str += stack.pop() return rev_str
def convert_int_to_bin(dec_num): s = Stack() while dec_num > 0: remainder = dec_num % 2 s.push(remainder) dec_num = dec_num // 2 Res = "" while not s.is_empty(): Res += str(s.pop()) return Res
class builderParseTree: """ 利用栈的先进后出特性和树构建解析时并计算 """ def __init__(self, fpexp): """ 初始化变量,创建栈和树的对象 :param fpexp: 表达式 """ self.fpexp = fpexp self.pStack = Stack() self.eTree = Tree('') def builderParseTree(self): """ 构建解析树 :return: 树 """ fplist = self.fpexp.split() self.pStack.push(self.eTree) currentTree = self.eTree for i in fplist: if i == '(': currentTree.insertLeft('') self.pStack.push(currentTree) currentTree = currentTree.getLeftNode() elif i not in '+-*/': currentTree.setRootValue(eval(i)) currentTree = self.pStack.pop() elif i in '+-*/': currentTree.setRootValue(i) currentTree.insertRight('') self.pStack.push(currentTree) currentTree = currentTree.getRightNode() elif i == ')': currentTree = self.pStack.pop() else: raise ValueError("Unknow Operator:" + i) return self.eTree
def baseConberter(decNumber, base): # 定义字符 digits = '0123456789ABCDEF' # 初始化栈 remstack = Stack() while decNumber > 0: rem = decNumber % 2 remstack.push(rem) decNumber = decNumber // base newString = "" while not remstack.isEmpty(): newString = newString + digits[remstack.pop()] return newString
def int_to_str(n, base): convert_string = "0123456789" rem_stack = Stack() #Code to push digits onto the stack while n > 0: if n < base: rem_stack.push(n) else: rem_stack.push(n % base) n = n // base #Code to get back the stack values equiv_string = "" while not rem_stack.isEmpty(): equiv_string = equiv_string + convert_string[rem_stack.pop()] return equiv_string if len(equiv_string) > 1 else "0"
def divideBy2(decNumber): # 初始化栈 remstack = Stack() # 截止条件为被除数大于0 while decNumber > 0: # 取余数 rem = decNumber % 2 # 余数入栈 remstack.push(rem) # 更新被除数 decNumber = decNumber // 2 # 当栈不空的时候,出栈 binString = "" while not remstack.isEmpty(): binString = binString + str(remstack.pop()) return binString
def convert_int_to_bin(stack: Stack, dec_num: str): if not dec_num.isnumeric(): return "Please enter a valid string with integer value" dec_num = int(dec_num) if dec_num == 0: return 0 binary_str = "" while dec_num > 0: dec_num, remainder = divmod(dec_num, 2) stack.push(remainder) while not stack.is_empty(): binary_str += str(stack.pop()) return binary_str
def is_paren_balanced(paren_string): s = Stack() is_balanced = True index = 0 while index < len(paren_string) and is_balanced: paren = paren_string[index] if paren in '({[': s.push(paren) else: if s.is_empty(): is_balanced = False else: top = s.pop() if not is_match(top, paren): is_balanced = False index += 1 if s.is_empty() and is_balanced: return True else: return False
def is_parenthesis_balanced(input_string): stack = Stack() is_balanced = True index = 0 while index < len(input_string) and is_balanced: paren = input_string[index] if paren in "([{": stack.push(paren) else: if stack.is_empty(): is_balanced = False else: top = stack.pop() if not is_match(top, paren): is_balanced = False index += 1 if stack.is_empty() and is_balanced: return True else: return False
def parChecker(symbolString): """ 普通情况:匹配括号(只有括号的符号) :param symbolString: :return: """ 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): # false balanced = False index += 1 return True if s.isEmpty() and not balanced else False
class transition: def __init__(self): self.stack = Stack() self.base_str = "" def toStr(self, num, base): """ 使用栈帧递归将任何数转换成进制数 :param num: 转换的数 :param base: 进制数 :return: 转换之后的数 """ coverString = "0123456789ABCDEF" if num < base: self.stack.push(coverString[num]) else: self.stack.push(coverString[num % base]) self.toStr(num//base, base) def show(self): for i in range(self.stack.size()): self.base_str += self.stack.pop() print(self.base_str)