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 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 infixToPostfix(infix): #infix = '(' + infix + ')' #Initialize Stack. opStack = Stack() output = "" #print(infix) #Loop Through All Tokens: for token in infix: #Case 1: Operator. if (isOperator(token)): while (not (opStack.isEmpty()) and isOperator(opStack.peek()) and ( (getAssociativity(token) == 'L' and getPrecedence(opStack.peek()) >= getPrecedence(token)) or (getAssociativity(token) == 'R' and getPrecedence(opStack.peek()) > getPrecedence(token)))): output += opStack.peek() opStack.pop() opStack.push(token) #Case 2: Left Paranthesis. elif (token == '('): opStack.push(token) #Case 3: Right Paranthesis. elif (token == ')'): while (not (opStack.isEmpty()) and opStack.peek() != '('): output += opStack.peek() opStack.pop() #Error-Checking: if (opStack.isEmpty()): # print("Empty Stack.") print(output) # return "ERROR" if (opStack.peek() == '('): opStack.pop() else: #Check For Non-Alpha Characters: if (not (token.isalpha())): # print("Not Alpha Not Space:", token, ".") return "ERROR" output += token #Append All Remaining Characters From opStack. while (not (opStack.isEmpty())): if (opStack.peek() == '(' or opStack.peek() == ')'): # print("Uh-OH! Mismatched Paranthesis") return "ERROR" output += opStack.peek() opStack.pop() #Return Output. return output
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 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): #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 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 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 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 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 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: 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 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: 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 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(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 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 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 convertToTree(postfix): #If Output convertInfixToPrefix Returned "ERROR" + Postfix = "RORRE". if (postfix == "RORRE"): return #Initialize Stack. convertToTree = Stack() for k in range(0, len(postfix)): #Case 1: Operator + Not-Negation if (isOperator(postfix[k]) and postfix[k] != "~"): #Pop Previous One TreeNode. prevOne = None if (not (convertToTree.isEmpty())): prevOne = convertToTree.peek() convertToTree.pop() #Pop Previous Two TreeNode. prevTwo = None if (not (convertToTree.isEmpty())): prevTwo = convertToTree.peek() convertToTree.pop() #Create + Set New TreeNode. currentNode = TreeNode(postfix[k]) currentNode.left = prevTwo currentNode.right = prevOne convertToTree.push(currentNode) #Case 2: Operator + Negation. elif (isOperator(postfix[k]) and postfix[k] == "~"): #Pop Previous One TreeNode. prevOne = None if (not (convertToTree.isEmpty())): prevOne = convertToTree.peek() convertToTree.pop() #Create + Set New TreeNode. currentNode = TreeNode(postfix[k]) currentNode.left = prevOne convertToTree.push(currentNode) #Case 3: New Leaf Node. else: currentNode = TreeNode(postfix[k]) convertToTree.push(currentNode) #Assert Only Root: # if(convertToTree.size() != 1): # print("Error In Construction. Must Review Input/Output.") #Set New Head Value = Top/Root of Stack. return convertToTree.peek()
def infixToPostfixEval(expr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() operandStack = Stack() postfixList = [] tokenList = expr.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()) str = " ".join(postfixList) tokenList2 = str.split() for token in tokenList2: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": return "Cannot be evaluated" elif token in "0123456789": operandStack.push(int(token)) elif token == '!': operand = operandStack.pop() result = math.factorial(operand) operandStack.push(result) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) x = str, "Evaluates to: ", operandStack.pop() return x
def infixToPostfixEval(infixExpre): prec = {} prec["!"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixExpre.split() #infix to postfix 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()) postfixExpre = (" ".join(postfixList)) #postfix to eval operandStack = Stack() tokenList = postfixExpre.split() for token in tokenList: if token in "0123456789": operandStack.push(int(token)) #seperate statements for factorial elif token == "!": operand1 = operandStack.pop() result = doFactorial(operand1) operandStack.push(result) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) return postfixExpre, operandStack.pop()
def balance_brackets(string): stack = Stack() open = "([{" close = ")]}" for i in string: if i in open: stack.push(i) else: if stack.isEmpty() or open.index(stack.peek()) != close.index(i): return False stack.pop() return stack.isEmpty()
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: # 这样识别有一个 bug,只能识别单个数字和字母,两位数及其以上都不行 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) ''' 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 infixToPostfixEval(infixexpr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["!"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() output: "" for token in tokenList: if token in "0123456789": postfixList.append(token) elif token == '(': topToken = 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()) output = " ".join(postfixList) operandStack = Stack() str1 = " ".join(postfixList) tokenLists = str1.split() for token in tokenLists: if token in "0123456789": operandStack.push(int(token)) else: if token == "!": result = math.factorial(operandStack.pop()) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) return output, operandStack.pop()
def direct_infix_evaluator(infixexpr: str) -> int or float: prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixEvaluation = Stack() tokenList = infixexpr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixEvaluation.push(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() found = False while topToken != '(' and not opStack.isEmpty(): found = True operator = topToken operand2 = postfixEvaluation.pop() operand1 = postfixEvaluation.pop() postfixEvaluation.push(doMath(operator, operand1, operand2)) topToken = opStack.pop() if not found: raise Exception('Unbalanced parentheses,too much ")"') else: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): operator = opStack.pop() operand2 = postfixEvaluation.pop() operand1 = postfixEvaluation.pop() postfixEvaluation.push(doMath(operator, operand1, operand2)) opStack.push(token) unbalanced_found = False while not opStack.isEmpty(): last = opStack.pop() if last == '(': unbalanced_found = True raise Exception('Unbalanced parentheses,too much "("') operator = last operand2 = postfixEvaluation.pop() operand1 = postfixEvaluation.pop() postfixEvaluation.push(doMath(operator, operand1, operand2)) return postfixEvaluation.pop()
def parCheckerAll(symbolString): s = Stack() for i in symbolString: if i in '[{(': s.push(i) elif i in ']})': if s.isEmpty(): return "Unbalanced" elif matches(i, s.peek()): s.pop() else: return "Unbalanced" if s.isEmpty(): return "Balanced" else: return "Unbalanced"
def infixEval(infixexpr): prec = {} prec["^"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] infixexpr = list(infixexpr) tokenList = [] for token in infixexpr: if token != ' ': tokenList.append(token) tokenList.append(' ') else: continue tokenList = ''.join(tokenList).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()) postfixExpr = " ".join(postfixList) solution = postfixEval(postfixExpr) return postfixExpr
def infixToPostfix(infixexpr): prec = {} # this dictionary assigns each operator a precedence value! prec["**"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [ ] # list that the postfix values will be added to after being put in the stack tokenList = infixexpr.split( ) # if two characters are together without spaces, they will be # represented as one token! :D 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 != '(': # ok this is key! the ('s are not added to the final list! :D postfixList.append(topToken) topToken = opStack.pop() # elif (not opStack.isEmpty()) and \ # (opStack.peek() == token) and token == "*" and tokenlist[token] + 1 == "*": # opStack.push(token+"*") # elif (not opStack.isEmpty()) and \ # (opStack.peek() == token) and token == "*" and tokenlist[token] - 1 == "*": # pass # elif (not opStack.isEmpty()) and \ # (opStack.peek() == token) and token == "*" and tokenlist[token] + 1 != "*": # opStack.push(token) 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 = new_prec # prec["*"] = 3 # prec["/"] = 3 # prec["+"] = 2 # prec["-"] = 2 # prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() # tokenList = parse_input(infixexpr) print(tokenList) for token in tokenList: # if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": if token not in operands: 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) return postfixList # print(infixToPostfix("A * B + C * D")) # print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )")) # print(infixToPostfix("( Aasdf + B ) * C - ( D - E ) * ( F + G )")) # print(infixToPostfix("( r2 > r1 && r1 == r2 ) || ( sucasa > ddfa )"))