def evalPost(postExpression): tokenStr = postExpression.split() operandStack = Stack() # index = 0 # while index < len(tokenStr): # token = tokenStr[index] for token in tokenStr : if token in "+-*/" : rightOp = operandStack.pop() leftOp = operandStack.pop() tempRes = mathsOp(token, leftOp,rightOp) operandStack.push(tempRes) else : # tempStr = [token] # index = index + 1 # while index < len(tokenStr) and token in "0123456789" : # token = tokenStr[index] # tempStr.append(token) # index = index + 1 # tempVal = float(str(tempStr)) # operandStack.push(tempVal) operandStack.push(float(token)) result = operandStack.pop() print(result) return result
def postExp(aStr): opStack = Stack() prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 1 prec["("] = 0 tokenStr = aStr.split() postExpressen = [] for token in tokenStr : if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token.isdigit(): postExpressen.append(token) elif token == "(" : opStack.push(token) elif token == ")" : token = opStack.pop() while token != "(": postExpressen.append(token) token = opStack.pop() else: # operator while opStack.isEmpty() == False and \ prec[opStack.peek()] >= prec[token] : postExpressen.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postExpressen.append(opStack.pop()) endRes = ' '.join(postExpressen) print(endRes) return endRes
def infixToPostfix(expression): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 tempStack = Stack() postfixList = [] tokenList = expression.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixList.append(token) elif token == "(": tempStack.push(token) elif token == ")": toptoken = tempStack.pop() while toptoken != '(': postfixList.append(toptoken) toptoken = tempStack.pop() else: while (not tempStack.isEmpty()) and (prec[tempStack.peek()] >= prec[token]): postfixList.append(tempStack.pop()) tempStack.push(token) while not tempStack.isEmpty(): postfixList.append(tempStack.pop()) return " ".join(postfixList)
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 = index + 1 if balanced and s.isEmpty(): return True else: return False
def divideBy2(decNumber): ''' 将整数不断除以 2,每次得到的余数就是由低到高的二进制 即最早得到余数,反而最后输出(把余数分别输出,而不是作为一个整体输出) 而起把数字变成字符处理,会简单些,输出是字符,不是数字 操作步骤: 1) 先建立一个空栈 2) 把十进制数除以 2 得到的余数进栈 3) 并把十进制数更新为除以 2 的商 4) 重复 2, 3 步骤, 直到十进制数为零为止 5) 出栈即可 实际操作中,因为把该功能使用函数实现,因此要返回一个值 所以要把栈中的数,输出后拼接在一起,再作为函数的返回值 而拼接使用字符拼接更为方便,字符相加即可, 故要把栈中数转换为字符 ''' remstack = Stack() 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 infixToPostfix(infixexpr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] #tokenList = infixexpr.split() tokenList = [char for char in infixexpr] # DA_20_20 mod 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() elif token != " ": # not affected by spaces now. # DA 20_20 mod 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 build_parse_tree(exp_string): exp_list = exp_string.split() # 表达式符号列表 parent_stack = Stack() # 存储父节点的栈 parse_tree = BinaryTree() # 解析树 node = parse_tree # 当前节点 for char in exp_list: if char == '(': # 创建并切换到左子节点 parent_stack.push(node) node.insert_left() node = node.left_child elif char in '+-*/': # 切换回父节点,设置父节点的值 node = parent_stack.pop() node.data = char # 创建并切换到右子节点 parent_stack.push(node) node.insert_right() node = node.right_child elif char in ')': # 切换回父节点 node = parent_stack.pop() elif char.isdigit(): # 设置当前节点的值 node.data = eval(char) else: raise ValueError(f'Unknown character: {char}') return parse_tree
def postfixEval(postfixExpr): operandStack = Stack() # 把后缀表达式以空格分割,并把结果存在列表 tokenList = postfixExpr.split() ''' # 该代码只能实现 10 以内的运算,10 以上的数字匹配没有 for token in tokenList: if token in "0123456789": operandStack.push(int(token)) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) ''' # 修改后,可以实现 10 以上的数字运算 for token in tokenList: if token in "+-*/": operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) else: operandStack.push(int(token)) return operandStack.pop()
def infixToPostfit(infixexpr): # 记录操作符优先级 prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] # 解析表达式到单词列表 tokenList = infixexpr.split() #print(tokenList) for token in tokenList: if token in "+-*/": while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: postfixList.append(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) # 操作符 return " ".join(postfixList) # 合成后缀表达式
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 string.ascii_uppercase: 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): exprList = infixexpr.split(' ') exprList.reverse() output = [] opStack = Stack() for token in exprList: if token == ')': opStack.push(token) elif token == '(': # pop until find the left-parenthesis. while True: op = opStack.pop() if op == ')': break else: output.append(op) elif token in ['+', '-', '*', '/']: # pop superior or equal operators then push operator. # do not pop `)` here. while not opStack.isEmpty() and opStack.peek() != ')': if isSuperiorOrEqual(opStack.peek(), token): output.append(opStack.pop()) else: break opStack.push(token) else: output.append(token) # retrieve the remain marks in operation stack. while not opStack.isEmpty(): output.append(opStack.pop()) output.reverse( ) # output is a reverse of prefix as a result of beginning reverse operation. return ' '.join(output)
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 string.ascii_uppercase: #操作数 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 infixToPostfix(infixexpr): prec = {} prec["**"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = tokenize(infixexpr) 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 infix_to_postfix(exp): stack = Stack() result = "" priority = {'^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0} for i in exp: # if alnum, then add to the result string if i.isalnum(): result += i # if (, then push it to the stack elif i == "(": stack.push(i) # if ) then, pop all the elements till you encounter (, including ( elif i == ")": while stack.peek() != "(": result += stack.pop() stack.pop() # if it's an operator, pop until the rank of the op in stack is >= the current op else: while not stack.isEmpty() and priority[ stack.peek()] >= priority[i]: result += stack.pop() stack.push(i) # pop all the remaining elements to result while not stack.isEmpty(): result += stack.pop() return result
def infix2postfix(infix): prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} opStack = Stack() postfixLst = [] token_lst = infix.split() for token in token_lst: if token in string.ascii_uppercase: postfixLst.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != "(": postfixLst.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]): # peek可看顶端元素 postfixLst.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixLst.append(opStack.pop()) return " ".join(postfixLst)
def infixToPostfix(infixexpr): prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} opStack = Stack() postfixList = [] try: 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) except: return f"Incorrect object type for infix expression.{TypeError}" while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList)
def infixToPostfix(infixexpr): #Specify the dictionary with precedence #Create a stack to keep operators. prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token in ('+', '-', '*', '/', '%'): while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: postfixList.append(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList)
def infix2postfix(infix): prec = { '(': 1, '+': 2, '-': 2, '*': 3, '/': 3, } stack = Stack() infix_list, postfix_list = infix.split(), [] for char in infix_list: if char in string.ascii_uppercase: postfix_list.append(char) elif char == '(': stack.push(char) elif char == ')': token = stack.pop() while token != '(': postfix_list.append(token) token = stack.pop() else: while not stack.is_empty() and prec[stack.peek()] >= prec[char]: postfix_list.append(stack.pop()) stack.push(char) while not stack.is_empty(): postfix_list.append(stack.pop()) return ' '.join(postfix_list)
def tranfortExpress(expression): priority = {} priority["/"] = 3 priority["*"] = 3 priority["+"] = 2 priority["-"] = 2 priority["("] = 1 emptyStack = Stack() emptyList = [] tokenList = expression.split() for token in tokenList: if token in string.ascii_uppercase: emptyList.append(token) elif token == '(': emptyStack.push(token) elif token == ')': topToken = emptyStack.pop() while topToken != '(': emptyList.append(topToken) topToken = emptyStack.pop() else: while (not emptyStack.isEmpty()) and \ (priority[emptyStack.peek()] >= priority[token]): emptyList.append(emptyStack.pop()) emptyStack.push(token) while not emptyStack.isEmpty(): emptyList.append(emptyStack.pop()) return ' '.join(emptyList)
def build_parse_tree(expr: str): """构建一棵解析树 expr: 全括号的算数表达式,运算符与数字之间用括号隔开 :param expr: str :return: BinaryTree """ ope_ls = expr.split() node_stack = Stack() tree = BinaryTree('') for e in ope_ls: if e == '(': tree.left_child = BinaryTree('') node_stack.push(tree) tree = tree.left_child elif e in "+-*/": tree.root = e tree.right_child = BinaryTree('') node_stack.push(tree) tree = tree.right_child elif e.isdigit(): tree.root = int(e) tree = node_stack.pop() elif e == ")": if node_stack.isEmpty(): return tree tree = node_stack.pop()
def infixToPostfix(infixexpr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: import pdb pdb.set_trace() 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 infix_to_postfix(infix_expr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = Stack() postfix_list = [] token_list = infix_expr.split() for token in token_list: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfix_list.append(token) elif token == '(': op_stack.push(token) elif token == ')': top_token = op_stack.pop() while top_token != "(": postfix_list.append(top_token) top_token = op_stack.pop() else: while (not op_stack.isEmpty()) and \ (prec[op_stack.peek()] >= prec[token]): postfix_list.append(op_stack.pop()) op_stack.push(token) while not op_stack.isEmpty(): postfix_list.append(op_stack.pop()) return " ".join(postfix_list)
def parChecker(strings): s=Stack() balanced=True i=0 while i <=len(strings)) and balanced: symbol=strings[i] if symbol="([{": s.push(symbol)
def toBinary(num): s = Stack() while num > 0: s.push(str(num % 2)) num = num // 2 dataList = [s.pop() for x in range(s.size())] return "".join(dataList)
def infix_to_postfix(infix_expr): """ Convert an infix mathematical expression into an postfix expression. :param infix_expr: String of infix expression :return: original infix expression as a postfix expression """ prec = {"**": 4, "//": 3, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1} op_stack = Stack() # Stack to hold operators postfix_list = [] # Where we will insert our postfix expression to print token_list = [] tmp_str = '' operator_str = '' for ch in infix_expr: # Convert expression into a list 3.0*5 + 4 if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or ch in "0123456789.": if operator_str != '': token_list.append(operator_str) operator_str = '' tmp_str = tmp_str + ch elif ch in "*+/-": if tmp_str != '': token_list.append(tmp_str) tmp_str = '' operator_str = operator_str + ch elif ch in "()": if tmp_str != '': token_list.append(tmp_str) tmp_str = '' elif operator_str != '': token_list.append(operator_str) operator_str = '' token_list.append(ch) if tmp_str != '': token_list.append(tmp_str) if tmp_str != '': token_list.append(operator_str) for token in token_list: # Go through each item in the list. if token not in "+-**//()": postfix_list.append(token) # add expression to list, not operator elif token == '(': # Notify that we'll have an operator of top priority coming up op_stack.push(token) elif token == ')': top_token = op_stack.pop() while top_token != '(': # Take the operator out of the stack and insert into our pfix list postfix_list.append( top_token) # continue for as many tokens were in the () top_token = op_stack.pop() elif token == '': pass else: while (not op_stack.isEmpty()) and \ (prec[op_stack.peek()] >= prec[token]): # compare operator precedence, decide which goes first postfix_list.append(op_stack.pop()) op_stack.push(token) while not op_stack.isEmpty(): postfix_list.append(op_stack.pop()) return " ".join(postfix_list)
def revstring(mystr): s = Stack() for i in mystr: s.push(i) #s1 = Stack() s1 = '' while not s.isEmpty(): s1 += s.pop() return s1
def revstring(orgStr): tempStack = Stack() resultStr = '' # push item to stack for s in orgStr: tempStack.push(s) while not tempStack.isEmpty(): resultStr += tempStack.pop() return resultStr
def divi_de_by_2(dec_number): remstack = Stack() while dec_number > 0: rem = dec_number % 2 remstack.push(rem) dec_number = dec_number // 2 bin_string = "" while not remstack.isEmpty(): bin_string = bin_string + str(remstack.pop()) return bin_string
def revstring(mystr): stack = Stack() for ch in mystr: stack.push(ch) newStr = "" while not stack.isEmpty(): newStr += stack.pop() return newStr
def base_covert(num, base): digits = "0123456789ABCDEF" converted_num = Stack() number = num while number > 0: number, rem = divmod(number, base) converted_num.push(rem) new_num = "" while not converted_num.isEmpty(): new_num += digits[converted_num.pop()] return new_num
def divideBy2(decNumber): remstack = Stack() 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 toStr(n, base): convertString = '0123456789ABCDEF' # can cover base upto 16 rStack = Stack() while n >0: if n<base: rStack.push(convertString[n]) else: rStack.push(convertString[n % base]) n= n // base res = '' while not rStack.isEmpty(): res = res + rStack.pop() return res
def baseConverter(decNumber, base): digits = "0123456789ABCDEF" remstack = Stack() while decNumber > 0: rem = decNumber % base remstack.push(rem) decNumber = decNumber // base newString = "" while not remstack.isEmpty(): newString = newString + digits[remstack.pop()] return newString
def postfixEval(postfixExpr): operandStack = Stack() tokenList = postfixExpr.split() for token in tokenList: if token in "0123456789": operandStack.push(int(token)) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token,operand1,operand2) operandStack.push(result) return operandStack.pop()
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): 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 = index + 1 if balanced and s.isEmpty(): return True else: return False