def operator_priority(formula): result_set = [] operator_list = Stack() operator = {'+': 2, '-': 2, '*': 3, '/': 3, '(': 1, ')': 1} for element in formula: if element in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or element in ( '1234567890'): result_set.append(element) # 操作数放入列表 elif element == '(': operator_list.push(element) elif element == ')': top_of_list = operator_list.pop() while top_of_list != '(': result_set.append(top_of_list) top_of_list = operator_list.pop() else: while (not operator_list.isEmpty()) and ( operator[operator_list.peek()] >= operator[element]): print(operator_list.peek()) print(operator[element]) result_set.append(operator_list.pop()) operator_list.push(element) while not operator_list.isEmpty(): result_set.append(operator_list.pop()) return result_set
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 match_parenthesis (symbolString): ## close any and all open parenthesises & return a "file" to be processed further... from pythonds.basic.stack import Stack s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol == "(": s.push(symbol+ str(index)) elif symbol == ")": if s.isEmpty(): balanced = False else: s.pop() index = index + 1 if balanced and s.isEmpty(): #print ("it is FINALLY balanced!") return symbolString elif balanced and not s.isEmpty(): #print "opening barace is not closed at " idx = int (s.pop().strip("(")) #print idx #print symbolString[idx] return (match_parenthesis(removeExtra(symbolString,idx))) else: #couldn't pop from stack #print "extra closing present at" #print index return (match_parenthesis(removeExtra(symbolString,index-1)))
def infixToPostfix(infixexpr): prec = {'^': 4, '*': 3, '/': 3, '+': 2, '-': 2, '(': 1} opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in '1234567890': postfixList.append(token) elif token == '(': opStack.push('(') 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): prec = {'*': 3, '/': 3, '+': 2, '-': 2, ')': 1} opStack = Stack() postfixList = [] tokenList = infixexpr.split() retokenList = reversed(tokenList) for token in retokenList: 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(reversed(postfixList))
def parChecker(symbolString): """ 功能:检查圆括号字符串是否平衡,如:'([]{})'是平衡字符串,'()[{'是非平衡字符串 实现:使'('为开始符号,当为'('压入栈,否则出栈 :param symbolString: 字符串 :return: bool """ s = Stack() balanced = True index = 0 while len(symbolString) > index and balanced: if symbolString[index] == '(': s.push(symbolString[index]) else: # 只要进入循环体栈就不可能为空,除非该字符串不是平衡的 if s.isEmpty(): balanced = False else: if symbolString[index] != ')': balanced = False s.pop() index += 1 # 只有在栈必须为空时才能是平衡字符串 if balanced and s.isEmpty(): return True else: return False
def infix_to_prefix(infix_expr): infix_expr = infix_expr.split() opers_stack = Stack() output = [] prec = { '*': 3, '/': 3, '+': 2, '-': 2, ')': 1, } for i in infix_expr[::-1]: if i == ')': opers_stack.push(i) elif i == '(': while True: oper = opers_stack.pop() if oper == ')': break output.append(oper) elif i in '+-*/': while not opers_stack.isEmpty() and prec[ opers_stack.peek()] >= prec[i]: output.append(opers_stack.pop()) opers_stack.push(i) else: output.append(i) while not opers_stack.isEmpty(): output.append(opers_stack.pop()) return ''.join(output[::-1])
def infixToPostfix(infixexpr): prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1, '^': 4} postfixList = [] opStack = Stack() tokenList = infixexpr.split() for token in tokenList: if token in string.uppercase or token.isdigit(): postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': top = opStack.pop() while top != '(': postfixList.append(top) top = 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 parChecker(symbolString): s = Stack() flag = True index = 0 while index < len(symbolString): symbol = symbolString[index] if symbol in "({[": s.push(symbol) else: if s.isEmpty(): flag = False else: top = s.pop() start = '([{' end = ')]}' if not start.index(top) == end.index(symbol): flag = False index = index + 1 if flag and s.isEmpty(): return True else: return False
def find_way(field: Field, start: Node, end: Node): nodes_to_visit = Stack() visited_nodes = set() nodes_to_visit.push(start) visited_nodes.add(start) current_node: Node = start while current_node != end and not nodes_to_visit.isEmpty(): current_node = nodes_to_visit.pop() for direction in ((-1, 0), (1, 0), (0, 1), (0, -1)): next_node = Node(current_node.x + direction[0], current_node.y + direction[1], current_node) if field.is_clear(next_node) and next_node not in visited_nodes: visited_nodes.add(next_node) nodes_to_visit.push(next_node) if next_node == end: current_node = next_node break if nodes_to_visit.isEmpty(): yield 'N' return yield 'Y' way: List[str] = list() while current_node is not None: way.append(current_node.to_str()) current_node = current_node.prev_node way.reverse() yield from way
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 parChecker1(symbolString): """ 功能:检查括号字符串是否平衡,如:'(()())'是平衡字符串,'()(('是非平衡字符串 实现:使'('为开始符号,当为'('压入栈,否则出栈 :param symbolString: 字符串 :return: bool """ s = Stack() balanced = True index = 0 # 用于检查出栈的括号是否对应匹配 matches = {'(': ')', '{': '}', '[': ']'} while len(symbolString) > index and balanced: if symbolString[index] in '({[': s.push(symbolString[index]) else: # 只要进入循环体栈就不可能为空,除非该字符串不是平衡的 if s.isEmpty(): balanced = False else: top = s.pop() # 括号必须对应匹配 if matches[top] != symbolString[index]: balanced = False index += 1 # 只有在栈必须为空时才能是平衡字符串 if balanced and s.isEmpty(): return True else: return False
def infixToPostfix(infixexpr): prec = {} prec["^"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr for token in tokenList: if token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() elif not isoperator(token): postfixList.append(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 postfixList
def infixToPostfix(infixexpr): # we will use a dictionary called prec to hold the precedence values for the operators. # This dictionary will map each operator to an integer that can be compared against the precedence levels of other operators (we have arbitrarily used the integers 3, 2, and 1). prec = {} prec["^"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: # defines the operands to be any upper-case character or digit. 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(k): prec = {} prec['*'] = 3 prec['/'] = 3 prec['+'] = 2 prec['-'] = 2 prec['('] = 1 postfix = [] opstack = Stack() token_list = list(k) for token in token_list: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfix.append(token) elif token == '(': opstack.push(token) elif token == ')': top_token = opstack.pop() while top_token != '(': postfix.append(top_token) top_token = opstack.pop() else: while (not opstack.isEmpty()) and (prec[opstack.peek()] >= prec[token]): postfix.append(opstack.pop()) opstack.push(token) while not opstack.isEmpty(): postfix.append(opstack.pop()) return "".join(postfix)
def parChecker(symbolString): """ single "(" ")" :param symbolString: :return: """ s = Stack() balanced = True # 匹配状态 index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol == "(": s.push(symbol) # symbol == ")" else: # s 是空栈 if s.isEmpty(): balanced = False else: s.pop() index = index + 1 # 最后,当所有符号都被处理后,栈应该是空的。而且是匹配的 if balanced and s.isEmpty(): return True else: return False
def infix_to_postfix(self): prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} op_stack = Stack() postfix_list = [] token_list = list(self.expr) for token in token_list: if token in self.var: 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 f"{self.expr} -> {''.join(postfix_list)}"
def infixToPostfix(infixexpr, prec): """ Converts the Infix expression of queries into postfix expression """ opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token.isalpha() and token not in (["OR", "AND", "NOT"]): stemWord = pObj.stem(token, 0, len(token) - 1) postfixList.append(stemWord) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: if (not opStack.isEmpty() and opStack.peek() == "NOT"): postfixList.append(opStack.pop()) while (not opStack.isEmpty()) and ( prec[opStack.peek()] >= prec[token] and token != "NOT"): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return postfixList
def __convert(tokens): postfix = [] opstack = Stack() for token in tokens: if token.isidentifier(): postfix.append(token) elif token == '(': opstack.push(token) elif token == ')': while True: temp = opstack.pop() if temp is None or temp == '(': break elif not temp.isidentifier(): postfix.append(temp) else: # must be operator if not opstack.isEmpty(): temp = opstack.peek() while not opstack.isEmpty() and precedence[temp] >= precedence[ token] and token.isidentifier(): postfix.append(opstack.pop()) temp = opstack.peek() opstack.push(token) while not opstack.isEmpty(): postfix.append(opstack.pop()) return postfix
def infixToPostfix(infixexpr): prec = {} prec["^"] = 4 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 or token in string.digits: 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): infixexpr = fix(infixexpr) prec = {} #prec['*'] = 3 prec['~'] = 4 prec['&'] = 3 #prec['/'] = 3 #prec['+'] = 2 prec['|'] = 2 #prec['-'] = 2 prec['('] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: #if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": if token.isalnum(): postfixList.append(token) elif token[0] == '(': 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(infixexpr): """ 中辍转后辍 :param infixexpr: :return: """ 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 par_checker(symbolstring): """ '([{'检验 :param symbolstring: :return: """ s = Stack() balance = True index = 0 while index < len(symbolstring) and balance: symbol = symbolstring[index] if symbol in '([{': s.push(symbol) else: if s.isEmpty(): balance = False else: top = s.peek() if matched(top, symbol): s.pop() else: balance = False index += 1 if balance and s.isEmpty(): return True else: return False
def infix_to_postfix(infixexpr): prec = {} prec["^"] = 4 prec["*"] = 3 prec["/"] = 3 prec["%"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token.isdigit(): 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 _postfix(self): opers_stack = Stack() output = [] prec = { '*': 3, '/': 3, '+': 2, '-': 2, '(': 1, } for i in self.infix_expr: if i == '(': opers_stack.push(i) elif i == ')': while True: oper = opers_stack.pop() if oper == '(': break output.append(oper) elif i in '+-*/': while not opers_stack.isEmpty() and prec[opers_stack.peek()] >= prec[i]: output.append(opers_stack.pop()) opers_stack.push(i) else: output.append(i) while not opers_stack.isEmpty(): output.append(opers_stack.pop()) return ''.join(output)
def infixToPostfix(infixexpr_arr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr_arr for token in tokenList: token = token.strip() # '33 ' -> '33' if re.match('^[a-zA-Z]+$', token) or re.match('^[0-9]+$', token): postfixList.append(token) elif re.match('^[a-zA-Z0-9]+$', token): # 'a22' print('Invalid identifier') break 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 postfixList
def match_parenthesis(symbolString): ## close any and all open parenthesises & return a "file" to be processed further... from pythonds.basic.stack import Stack s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol == "(": s.push(symbol+ str(index)) elif symbol == ")": if s.isEmpty(): balanced = False else: s.pop() index = index + 1 if balanced and s.isEmpty(): return symbolString elif balanced and not s.isEmpty(): idx = int (s.pop().strip("(")) return (match_parenthesis(removeExtra(symbolString,idx))) else: #couldn't pop from stack return (match_parenthesis(removeExtra(symbolString,index-1)))
def parChecker1(symbolString): """ serveral "(" "[" "{" :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): balanced = False 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 'ABCDEFGHIJKLMNOPQRSTUMWXYZ' 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 = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} opStack = Stack() postfixList = [] tokenList = list(infixexpr) for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".lower() 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): if not balanceString(expression): raise SyntaxError('Parentheses are not balanced in the expression') precedence = {'**':4, '^': 4, '*': 3, '/': 3, '+': 2, '-': 2, '(': 1, ')': 1 } # newExpression = expression.replace(' ', '') expList = expression.split(' ') opStack = Stack() output = [] # for character in newExpression: for item in expList: if item in precedence: if item == '(': opStack.push(item) elif item == ')': poppedItem = opStack.pop() while poppedItem != '(': output.append(poppedItem) poppedItem = opStack.pop() else: while not opStack.isEmpty() and precedence.get(opStack.peek()) >= precedence.get(item): output.append(opStack.pop()) opStack.push(item) else: output.append(item) while not opStack.isEmpty(): output.append(opStack.pop()) return ' '.join(output)
def rule_to_postfix(infix_rule): prec = dict() prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = Stack() postfix_list = [] token_list = infix_rule.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 postfix_list
def infixToPostfix(self, s): prec = {} prec["~"] = 5 prec["&"] = 4 prec["|"] = 3 prec["=>"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] i = 0 while i != (len(s) - 1): if s[i] == ' ': i = i + 1 continue if s[i] == '=': token = s[i] + s[i + 1] i = i + 1 else: token = s[i] k = i + 1 # print(token) if token.isupper(): for j in range(k, len(s) - 1): word = s[j] #not word.isupper() and if word not in ['|', '&', '=']: if word == ' ': j = j + 1 i = i + 1 continue if (s[j] == ')' and s[j - 1] == ')'): continue else: token = token + word i += 1 else: break postfixList.append(self.add_predicate(token)) #postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': #print(topToken) postfixList.append(self.add_predicate(topToken)) topToken = opStack.pop() else: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(self.add_predicate(opStack.pop())) opStack.push(token) i = i + 1 while not opStack.isEmpty(): ch = opStack.pop() if ch != '(': postfixList.append(self.add_predicate(opStack.pop())) return(postfixList)
def infixToPostfix(infixexpr): prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1, '^': 4} postfixList = [] opStack = Stack() tokenList = infixexpr.split() for token in tokenList: if token in string.uppercase or token.isdigit(): postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': top = opStack.pop() while top != '(': postfixList.append(top) top = 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 calculatorEval(toklist): opTokens = "*/+-" prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} numStack = Stack() opStack = Stack() for tok in toklist: if tok.isdigit(): numStack.push(int(tok)) elif tok in opTokens: if opStack.isEmpty(): opStack.push(tok) else: if prec[tok] > prec[opStack.peek()]: opStack.push(tok) else: process(numStack, opStack) opStack.push(tok) elif tok == "(": opStack.push(tok) elif tok == ")": while opStack.peek() != "(": process(numStack, opStack) opStack.pop() while not opStack.isEmpty(): process(numStack, opStack) return numStack.pop()
def infix_to_prefix(infixexpr): prec = {} prec["^"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec[")"] = 1 prec["("] = 1 opStack = Stack() prefixStack = Stack() tokenList = infixexpr[::-1].split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" or token in "0123456789": prefixStack.push(token) elif token == ')': opStack.push(token) elif token == '(': topToken = opStack.pop() while topToken != ')': prefixStack.push(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]): prefixStack.push(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): prefixStack.push(opStack.pop()) output = "" while not prefixStack.isEmpty(): output += prefixStack.pop() + " " return output
def infix_to_postfix(self, infixexpr): opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if BoolParser.isBoolVariable(token): # if token is a boolean variable, just append to list postfixList.append(token) elif token == '(': # start a new nested expression in the stack opStack.push(token) elif token == ')': # end the nested expression by moving the operators # from the stack to the list (i.e. in reverse order) topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and \ (BoolParser.PREC[opStack.peek()] >= BoolParser.PREC[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return postfixList
class Conversion (object) : def __init__(self): self.prec = {} self.init_prec() self.op_stack = Stack() #operators will be kept in this stack self.output_list = [] #any postfix or prefix expression will be written in the list self.token_list = [] #initial expression will be read and kept in this list self.operands = [] self.init_operand() def init_prec(self) : self.prec["*"] = 3 self.prec["/"] = 3 self.prec["+"] = 2 self.prec["-"] = 2 self.prec["("] = 1 def init_operand(self) : self.operands = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" def re_init(self) : #After any operation, the stack should be empty self.op_stack = Stack() self.output_list = [] self.token_list = [] def infixToPostfix(self,infixexpr) : '''The function will read an infix expression and write its corresponding expression in the output_list doesn't return anything but alters the output_list''' self.re_init() self.token_list = infixexpr.split() for token in self.token_list : if token in self.operands : self.output_list.append(token) elif token == '(' : self.op_stack.push(token) elif token == ')' : top_token = self.op_stack.pop() while top_token != '(' : self.output_list.append(top_token) top_token = self.op_stack.pop() else : while (not self.op_stack.isEmpty()) and \ (self.prec[self.op_stack.peek()] >= self.prec[token]) : self.output_list.append(self.op_stack.pop()) self.op_stack.push(token) while not self.op_stack.isEmpty() : self.output_list.append(self.op_stack.pop()) def getOutput(self) : return " ".join(self.output_list) def infixToPrefix(self, infixexpr) : pass
def infix_to_post(str): tokenList = str.split() length = len(tokenList) cnt_pa = 0 cnt_op = 0 for token in tokenList: if token not in "ABCDEFGHIJKLMNOPQRST" and token not in "0123456789" and token not in "+-*/" and token not in "()": raise RunTimeError("Wrong input") if token in "()": count_pa += 1 if token in "+-*/" count_op += 1 if length - cnt_pa != 2 * cnt_op + 1: raise RunTimeError("Wrong input") opStack = Stack() postFixList = [] prec = {} prec['('] = 1 prec[')'] = 1 prec['+'] = 2 prec['-'] = 2 prec['*'] = 3 prec['/'] = 3 for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRST" or token in "0123456789": postFixList.append(token) elif token == "(": opStack.push(token) elif token == ")": topToken = opStack.pop() if 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 revstring(mystr): myStack = Stack() for i in mystr: myStack.push(i) revstr = '' while not myStack.isEmpty(): revstr = revstr + myStack.pop() return revstr
def revstring_mine(mystr): s = Stack() for char in mystr: s.push(char) revstr = '' while not s.isEmpty(): revstr += s.pop() return revstr
def revstring(mystr): s = Stack() new_mystr = '' for i in mystr: s.push(i) while not s.isEmpty(): new_mystr = new_mystr+s.pop() return new_mystr
def infixToPostfix(infixepr): """Create an empty stack called opstack for keeping operators. Create an empty list for output. Convert the input infix string to a list by using the string method split. Scan the token list from left to right. If the token is an operand, append it to the end of the output list. If the token is a left parenthesis, push it on the opstack. If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each operator to the end of the output list. If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the opstack that have higher or equal precedence and append them to the output list. When the input expression has been completely processed, check the opstack. Any operators still on the stack can be removed and appended to the end of the output list. """ prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixepr.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 revstring(mystr): # your code here reversed = "" string_stack = Stack() for char in mystr: string_stack.push(char) while not string_stack.isEmpty(): last = string_stack.pop() reversed += last return reversed
def parChecker1(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 += 1 if balanced and s.isEmpty(): return True else: return False
def divide_by_2(num): rem_stack = Stack() # putting my stack in action while num > 0: rem = num % 2 # remainder variable rem_stack.push(rem) # push the remainder in my stack num = num // 2 # divide my num by two bin_string = '' # create my binary string while not rem_stack.isEmpty(): bin_string = bin_string + str(rem_stack.pop()) # pop the remainder from my stack return bin_string # get my binary string
def parChecker(symbolString): s = Stack() # stack method applied balanced = True # bool value true if par is balanced index = 0 while index < len(symbolString) and balanced: # loops through the symbolString symbol = symbolString[index] # assign a symbol var to the symbolString index if symbol == "(": # condition set s.push(symbol) # push the symbol on the stack else: if s.isEmpty(): # when stack is empty balanced = False # no balance else: s.pop() # else remove the the symbol from the stack index = index + 1 # start up indexing of the symbolString if balanced and s.isEmpty(): return True else: return False
def divide_by_two(decimal): stack = Stack() while decimal > 0: remainder = decimal % 2 stack.push(remainder) decimal = decimal // 2 binary = '' while not stack.isEmpty(): binary += str(stack.pop()) return binary
def parChecker(symbolString): s = Stack() balanced = True index = 0 while balanced and index < len(symbolString): curr = symbolString[index] if curr in '([{': s.push(curr) else: if s.isEmpty(): balanced = False else: top = s.pop() if not matches(top, curr): balanced = False index += 1 if balanced and s.isEmpty(): return True else: return False
def revstring(sg): s = Stack() lst = [i for i in sg] res = [] for c in lst: s.push(c) while not s.isEmpty(): res.append(s.pop()) return "".join(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 parChecker(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] print("Current symbol is " , symbol) if symbol in "([{": s.push(symbol) else: if s.isEmpty(): balanced = False else: top = s.pop() #print(" top position is " , top) if not matches(top,symbol): balanced = False index = index + 1 if balanced and s.isEmpty(): return True else: return False
def divideBy2(decNumber): s = Stack() while decNumber > 0: rem = decNumber % 2 s.push(rem) decNumber //= 2 res = [] while not s.isEmpty(): res.append(str(s.pop())) return "".join(res)
def baseConverter(decNumber, base): digits = string.digits + string.uppercase s = Stack() while decNumber > 0: rem = decNumber % base s.push(rem) decNumber /= base res = [] while not s.isEmpty(): res.append(str(digits[s.pop()])) return "".join(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 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
def parChecker(String) : '''read a string and check whether it has balanced parathesis''' s = Stack() balance = True for char in String : if char == '(' : s.push(char) elif char != ')' : pass elif char == ')' : if s.isEmpty() : balance = False else : s.pop() return balance
def baseConverter(decNumber,base): digits = "0123456789ABCDEF" remstack = Stack() while decNumber > 0: rem = decNumber % base remstack.push(rem) decNumber = decNumber // base binString ='' while not remstack.isEmpty(): binString += digits[(remstack.pop())] return binString