def buildParseTree(fpexp, aviableOperators=["and", "And", "or", "Or", ")"]): 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 aviableOperators: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in aviableOperators: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
def postorder(root): # 以非递归的方式遍历二叉树:后序遍历 if root == None: return None stack1 = Stack() stack2 = Stack() stack1.push(root) while not stack1.isEmpty(): cur = stack1.pop() stack2.push(cur) if cur.left != None: stack1.push(cur.left) if cur.right != None: stack1.push(cur.right) while not stack2.isEmpty(): print(stack2.pop().val)
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 checkSatisfiability(self, postFixList): propStack = Stack() p = re.compile('[a-zA-Z0-1]') for op in postFixList: if op == 'ID' or p.match(op): propStack.push(Symbol(op)) elif op in ['NOT', '!']: propStack.push(Not(propStack.pop())) elif op in ['AND', '/\\', ',', 'COMMA']: p2 = propStack.pop() p1 = propStack.pop() propStack.push(And(p1, p2)) elif op in ['OR', '\\/']: p2 = propStack.pop() p1 = propStack.pop() propStack.push(Or(p1, p2)) elif op in ['IFF', '<=>']: p2 = propStack.pop() p1 = propStack.pop() propStack.push(Iff(p1, p2)) elif op in ['IMPLIES', '=>']: p2 = propStack.pop() p1 = propStack.pop() propStack.push(Implies(p1, p2)) print("propStack size: ", propStack.size()) if propStack.size() == 1: p3 = propStack.pop() # print ("Expression for satisfiability:", p3) print("Is sat or not : ", is_sat(p3)) else: print("Error while checking Is sat or not")
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(int(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 return eTree
def parChecker(symbolString): """括号匹配 在数学运算里面,括号必须以匹配的方式出现,比如(1 + 1) * 2, ()是匹配的,解决方法是把(作为判断条件,如果括号为'('则入栈, 为')'则出栈,如果最后栈为空则证明括号匹配 """ 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 elif symbol == ")": s.pop() index = index + 1 if balanced and s.isEmpty(): return True else: return False
def infix_to_postfix(infixexpr: str): prec = {} prec["."] = 2 prec["|"] = 1 prec["*"] = 3 # prec["+"] = 2 prec["(."] = 0 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890()": 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(query): query_list = word_tokenize(query) stack = Stack() postfix = [] for word in query_list: if word not in OPERATORS: postfix.append(word) elif word == '(': stack.push(word) elif word == ')': top = stack.pop() while top != '(': postfix.append(top) top = stack.pop() else: while not stack.isEmpty() and PRECIDENT[ stack.peek()] >= PRECIDENT[word]: postfix.append(stack.pop()) stack.push(word) while not stack.isEmpty(): postfix.append(stack.pop()) return ' '.join(postfix)
def postfixEval(postfixExpr, variables): operandStack = Stack() tokenList = postfixExpr.split() for token in tokenList: if token not in "@#&|": token_nfa = nfaclasses1.nfa.init_from_min(token, token, variables) operandStack.push(token_nfa) else: if token == "|": operand2 = operandStack.pop() operand1 = operandStack.pop() result_nfa = nfaclasses1.nfa.init_or_nfa( operand1.name + operand2.name, operand1, operand2, variables) operandStack.push(result_nfa) elif token == "&": operand2 = operandStack.pop() operand1 = operandStack.pop() result_nfa = nfaclasses1.nfa.init_and_nfa( operand1.name + operand2.name, operand1, operand2, variables) operandStack.push(result_nfa) elif token == "@": operand2 = operandStack.pop() result_nfa = nfaclasses1.nfa.init_star_nfa( operand2.name + "@", operand2, variables) operandStack.push(result_nfa) elif token == "#": operand2 = operandStack.pop() result_nfa = nfaclasses1.nfa.init_plus_nfa( operand2.name + "#", operand2, variables) operandStack.push(result_nfa) return operandStack.pop()
def ParChecker(symbolString): #检测括号的函数,参数为一个全为括号的字符串 checktool = Stack() # 用于括号检测的栈 balanced = True #balanced作为括号是否匹配的检测值,一开始被设为True index = 0 # 用于作为下标从从左往右访问symbolString中的括号 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol == '(': checktool.push(symbol) # 如果symbol是左括号,将其压入栈中 else: if checktool.isEmpty( ): # 若在未检测到最后一个闭括号时检测栈已经为空,则证明不匹配,balanced设定为False balanced = False else: checktool.pop() # 若栈非空,则弹出一个'('作为匹配 index = index + 1 #当循环结束时候,有三种情况,第一,若完全匹配,此时栈为空。balanced=True #第二,若不完全匹配,(1)后括号有剩余,栈为空,balanced==False #(2)后括号匹配完成但前括号有剩余,栈非空,balanced=True if balanced and checktool.isEmpty( ): #由上述分析可知,只有当balanced=True且栈为空时,才代表括号完全匹配 return True else: return False
def infixToPostfix(infixexpr): prec = {} prec["@"] = 4 prec["#"] = 4 prec["&"] = 3 prec["|"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token not in "@#&|()": 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(formula): formulalist = formula.split() #['(','3','+','(','4','*','5',')',')'] rootStack = Stack() #用于跟踪父节点 Tree = BinaryTree('') #创建一个二叉树 rootStack.push(Tree) currentTree = Tree for i in formulalist: if i == '(': currentTree.insertLeft('') rootStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parent = rootStack.pop() cerrentTree = parent elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') rootStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = rootStack.pop() else: raise ValueError #raise的参数必须是一个异常实例或者一个异常类:ValueError无效参数 return Tree
def query_processing(user_query): '''Query processing: 1. transform infix format to postfix format; ref: https://bit.ly/28OMA5X 2. deal with the wildcard ''' # Split the query into a list of word, including the parentheses pattern = re.compile(r"([.()!])") tmp = (pattern.sub(" \\1 ", user_query)).split(" ") tokenList = list(filter(None,tmp)) # Transform infix to postfix opStack = Stack() postfixList = [] prec = {} prec["("] = 1 prec["AND"] = 2 prec["OR"] = 2 prec["AND_NOT"] = 2 for t in tokenList: if (not(isOperator(t))): postfixList.append(t) elif t == "(": opStack.push(t) elif t == ")": topToken = opStack.pop() while topToken != "(": postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[t]): postfixList.append(opStack.pop()) opStack.push(t) while (not opStack.isEmpty()): postfixList.append(opStack.pop()) return " ".join(postfixList)
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
def postfix_converter(exp): exp = ['('] + exp + [')'] #print(exp) i = 0 operator_stack = Stack() postfix_exp = [] while (i < len(exp)): if (exp[i] in numbers): postfix_exp.append(exp[i]) if (exp[i] == '('): operator_stack.push(exp[i]) if (exp[i] == ')'): while (operator_stack.peek() != '('): postfix_exp.append(operator_stack.pop()) operator_stack.pop() if (exp[i] in precedence_dict.keys()): if (operator_stack.peek() == '('): operator_stack.push(exp[i]) elif (precedence_dict[exp[i]] < precedence_dict[operator_stack.peek()]): operator_stack.push(exp[i]) else: postfix_exp.append(exp[i]) postfix_exp.append(operator_stack.pop()) i += 1 return postfix_exp
def parChecker(symbolString): s = Stack() flag = True index = 0 while index < len(symbolString) and flag: 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 += 1 if flag and s.isEmpty(): return True else: return False
def conversion(line): postfix = '' operators = [';', '+', '-', '*', '/', '%', '=', ',', '.', ':'] stack = Stack() line = line.replace(' ', '') for i in range(len(line)): if line[i].isdigit(): postfix += line[i] if (i + 1 >= len(line) or line[i + 1].isdigit() == False): postfix += ' ' elif precedence_rank(line[i]) != 0: while ((stack.isEmpty() == False) and (precedence_rank(stack.peek()) >= precedence_rank(line[i])) and stack.peek() != '('): if line[i] in operators and line[i + 1] in operators: postfix += ' ' postfix += stack.peek() stack.pop() postfix += ' ' stack.push(line[i]) elif line[i] == '(': stack.push(line[i]) elif line[i] == ')': while stack.isEmpty() == False and (stack.peek() != '('): postfix += stack.peek() postfix += ' ' stack.pop() stack.pop() while stack.isEmpty() == False: postfix += stack.pop() postfix += ' ' return postfix
def postfixCal(postfixequa): postfixequa = postfixequa.split() operandStack = Stack() for token in postfixequa: if token.isdigit(): operandStack.push(token) else: operand2 = int(operandStack.pop()) operand1 = int(operandStack.pop()) if token == '+': operandStack.push(operand1 + operand2) elif token == '-': operandStack.push(operand1 - operand2) elif token == '*': operandStack.push(operand1 * operand2) elif token == '/': #should return integer to the stack operandStack.push(operand1 // operand2) elif token == '%': operandStack.push(operand1 % operand2) elif token == '^': operandStack.push(operand1 ** operand2) return operandStack.pop()
def parChecker(mystr): s = Stack() balanced = True index = 0 while index < len(mystr) and balanced: a = mystr[index] if a == "(" or a == "[" or a == "{": s.push(a) elif a == " ": pass else: if s.isEmpty(): balanced = False else: q = s.pop() if a == ")" and q != "(": balanced = False if a == ")" and q != "(": balanced = False if a == "}" and q != "{": balanced = False index = index + 1 if balanced and s.isEmpty(): return True else: return False
def parsetree(expression): inittr = TreeNode(None) # print(tr) pStack = Stack() pStack.push(inittr) tr = inittr for val in expression.split(): print(val) if val == LEFT_Bracket: tr.insertleft('') pStack.push(tr) tr = tr.getleft() elif val in OPERATORS: tr.setvalue(val) tr.insertright('') pStack.push(tr) tr = tr.getright() elif val == RIGHT_Bracket: tr = pStack.pop() else: tr.setvalue(int(val)) parent = pStack.pop() tr = parent # print(preorder(tr)) # print(pStack) return inittr
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 buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) for i in fplist: if i == '(': # 如果当前符号是“(”,添加一个新节点作为当前节点的左子节点,并且下降到左子节点 eTree.insertLeft('') pStack.push(eTree) eTree = eTree.getLeftChild() elif i not in ['+', '-', '/', '*', ')']: # 如果当前符号是数字,将当前节点的根值设置为该数字并返回父节点 eTree.setRootVal(int(i)) parent = pStack.pop() eTree = parent elif i in ['+', '-', '/', '*']: eTree.setRootVal(i) eTree.insertRight('') pStack.push(eTree) eTree = eTree.getRightChild() elif i == ')': eTree = pStack.pop() else: raise ValueError return eTree
class FriendParser(HTMLParser): s = Stack() friends = [] current_head = "" data = "" header = ['html', 'body', 'div', 'h2'] expected = ['html', 'body', 'div', 'ul', 'li'] def handle_starttag(self, tag, attrs): self.s.push(tag) if self.s == self.expected: self.data = "" def handle_endtag(self, tag): if self.s == self.expected: self.friends.append(Friend(self.data, self.current_head)) self.s.pop() def handle_data(self, data): if self.s == self.expected: self.data += data if self.s == self.header: self.current_head = data def handle_entityref(self, name): if self.s == self.expected: self.data += name def handle_charref(self, name): if self.s == self.expected: self.data += name #hexadecimal bug - unichr/chr? - strip/map?
def inToPostfix(expression): expression = expression.replace(" ","") open_count = 0 closed_count = 0 new_exp = [] numeric_buffer = [] prev = '' for each in expression: if each not in "1234567890+-/()*": print("invalid expression") return "invalid syntax" if prev in "+-*/" and each in "+-*/": print("invalid expression") return "invalid syntax" if each in "+-()*/": if each == "(": open_count+=1 if each == ")": closed_count+=1 if numeric_buffer!=[]: new_exp.append(int(''.join(numeric_buffer))) numeric_buffer = [] new_exp.append(each) else: numeric_buffer.append(each) prev = each if open_count!=closed_count: print("brackets mismatch") return "invalid syntax" if numeric_buffer!=[]: new_exp.append(int(''.join(numeric_buffer))) expression = new_exp print("INFIX: " +str(expression)) dict_exp = {'/':4, '*':3, '+':2, '-':1, '(':0} operations = Stack() output = [] for ch in expression: if ch=='(': operations.push(ch) elif type(ch)==int: output.append(ch) elif ch==')': chMain = operations.pop() while chMain!='(': output.append(chMain) chMain = operations.pop() else: while(not operations.isEmpty()) and (dict_exp[operations.peek()]\ >= dict_exp[ch]): output.append(operations.pop()) operations.push(ch) while not operations.isEmpty(): output.append(operations.pop()) return output
def revstring(revstr=""): alist = Stack() blist = '' for ch in revstr: alist.push(ch) while not alist.isEmpty(): blist += alist.pop() return blist
def revstring(mystr): m = Stack() st = mystr for i in st: m.push(i) # print(m.size())pyt while not m.isEmpty(): print(m.pop(), end='')
def revstring(mystr): m = Stack() word = '' for i in mystr: m.push(i) for k in range(len(mystr)): word += m.pop() print(word)
def balanced_parenthesis(s): p = Stack() for ch in s: if(ch=="("): p.push(ch) elif(ch==")"): p.pop() return p.isEmpty()
def revstring(mystr): s = Stack() ss = '' for i in mystr: s.push(i) while not s.isEmpty(): ss += s.pop() return ss
def revstring(mystr): myStack = Stack() for ch in mystr: myStack.push(ch) revstr = '' while not myStack.isEmpty(): revstr = revstr + myStack.pop() return revstr