def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() # following parent node eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() elif i not in ['+', '-', '*', '/', ')']: # operands try: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent except ValueError: raise ValueError( "Token '{}' is not a valid integer.".format(i)) return eTree
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 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 buildParseTree(fpexp): fplist = split_expression(fpexp) # Exercise question pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() elif i not in ['+', '-', '*', '/', ')']: try: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent except ValueError: raise ValueError("token '{}' is not a valid integer".format(i)) return eTree
def infixToPostfix(infixQuery, term): queryList = infixQuery.split() queryStack = Stack() postfixQuery = [] precOperator = {} precOperator["not"] = 4 precOperator["and"] = 3 precOperator["or"] = 2 precOperator["("] = 1 for query in queryList: if query in term: postfixQuery.append(query) indexNext = queryList.index(query) + 1 if indexNext != len(queryList) and (queryList[indexNext] in term): queryStack.push("and") elif query == '(': queryStack.push(query) elif query == ')': stackTeratas = queryStack.pop() while stackTeratas != '(': postfixQuery.append(stackTeratas) stackTeratas = queryStack.pop() else: while (queryStack.isEmpty() != True) and ( precOperator[queryStack.peek()] >= precOperator[query]): postfixQuery.append(queryStack.pop()) queryStack.push(query) while (queryStack.isEmpty() != True): postfixQuery.append(queryStack.pop()) return postfixQuery
def buildParseTree(fpexp): fplist = mystr = re.findall(r'\s*([()+*/-]|\d+)', fpexp) pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() elif i not in ['+', '-', '*', '/', ')']: try: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent except ValueError: raise ValueError("token '{}' is not a valid integer".format(i)) return eTree
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 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 buildParseTree(math_exp): lst = math_exp.split() pstack = Stack() etree = BinaryTree("") pstack.push(etree) currentTree = etree for i in lst: if i == "(": currentTree = currentTree.insertLeft("") # 此时尚在根结点(父节点) pstack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in "+-*/)": currentTree.setRootVal(eval(i)) parent = pstack.pop() currentTree = parent elif i in "+-*/": currentTree.setRootVal(i) currentTree.insertRight("") pstack.push(currentTree) elif i == ")": currentTree = pstack.pop() else: raise ValueError("Unknow Operator:{}".format(i)) return currentTree
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for word in fplist: if word == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif word not in '+-*/)': currentTree.setRootVal(eval(word)) currentTree = pStack.pop() elif word in '+-*/': currentTree.setRootVal(word) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif word == ')': currentTree = pStack.pop() else: raise ValueError('运算表达式出现问题:' + word) return eTree
def buildParseTree(expr): lot = expr.split() tree = BinaryTree("") posStack = Stack() posStack.push(tree) currentTree = tree for token in lot: if token == "(": currentTree.insertLeft("") posStack.push(currentTree) currentTree = currentTree.getLeftChild() elif token == ")": currentTree = posStack.pop() elif token in ["and", "or"]: currentTree.setRootVal(token) currentTree.insertRight("") posStack.push(currentTree) currentTree = currentTree.getRightChild() elif token == "not": parent = posStack.pop() currentTree = parent currentTree.setRootVal(token) posStack.push(currentTree) currentTree = currentTree.getLeftChild() elif token in ["1", "0"]: currentTree.setRootVal(int(token)) parent = posStack.pop() currentTree = parent return tree
def creatS(self,fpexp): fplist = fpexp.split() p_stack = Stack() e_tree = BinaryTree('') p_stack.push(e_tree) current_tree = e_tree for i in fplist: if i == "(": current_tree.insert_left('') p_stack.push(current_tree) current_tree = current_tree.get_left_child() elif i in "'and','or'": current_tree.set_root_val(i) current_tree.insert_right('') p_stack.push(current_tree) current_tree=current_tree.get_right_child() elif i in "'not'": current_tree = p_stack.pop() current_tree.set_root_val(i) current_tree.insert_left(False) current_tree.insert_right('') p_stack.push(current_tree) current_tree=current_tree.get_right_child() elif i == ')': current_tree = p_stack.pop() else: current_tree.set_root_val(i) parent = p_stack.pop() current_tree = parent if i not in self.symbols: self.symbols.append(i) self.val=e_tree
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 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 buildParseTree(fpexp): fplist = format_fpelist(fpexp) # fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parrent = pStack.pop() currentTree = parrent elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
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 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 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 buildParseTree(fpexp): ####tokenize the expression to follow the rules: fplist=fpexp.split() pStack=Stack() eTree=BinaryTree('') pStack.push(eTree) currentTree=eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree=currentTree.getLeftChild() elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree=currentTree.getRightChild() elif i == ')': currentTree=pStack.pop() elif i not in ['+', '-', '*', '/',')']: try: currentTree.setRootVal(int(i)) parent=pStack.pop() currentTree=parent except ValueError: raise ValueError("token '{}' is not a valid interger'.format(i)) return eTree
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 buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in '+-*/)': currentTree.setRootVal(eval(i)) parent = pStack.pop() currentTree = parent elif i in '+-*/': currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError("Unknown Operator: " + i) return eTree
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 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 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 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 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 = {} 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 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 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 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 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 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