def chkid_allrecord(self,m,rr1): # que = "SELECT * FROM wp_2015ptainsuracelist where frm_id='%s';" % (rr1) # rr=m.db.query(que) idData = (str(rr1),) que = """SELECT * FROM """+self.table+""" where frm_id==?""" rr=m.dbsql3.data_query(que,idData,False) print rr p = Stack() print(rr) if rr: for i in rr[0]: p.push(i) rrr=p.seek() OR = rrr[18] ins = rrr[16] reg = rrr[15] trans = rrr[19] print "Pass chkid_allrecord!******************" if OR=='' and ins==0 and reg==0 and trans=='': return 'False1',rrr if OR!='' and ins==0 and trans!='': return 'True1',rrr if OR!='' and ins!=0 and trans!='': return 'True2',rrr else: return 'False2'
def chkid_len(self,main,a,b=None,c=None,d=None,e=False): if e: if len(a)==8 or len(a)==10 or a.count('x')==4: return True else: self.alert(main,'ID Less than 8 or 10!','ID length allowed is 8 or 10 \n You have #'+str(len(a))+' digits.') return False else: print("self table===="+self.table) print("Check by name is activated!") # que = "SELECT * FROM wp_2015ptainsuracelist where frm_stdname='%s' AND frm_std_middle_name='%s' AND frm_std_last_name='%s';" % (b,c,d) que = """SELECT * FROM """+self.table+""" where frm_stdname=? AND frm_std_middle_name=? AND frm_std_last_name=?""" fullname = (str(b),str(c),str(d)) rr=main.dbsql3.data_query(que,fullname) p = Stack() print(b+" "+c+" "+d) print("student name! search") print(rr) if rr: for i in rr[0]: p.push(i) rrr=p.seek() OR = rrr[18] ins = rrr[16] reg = rrr[15] trans = rrr[19] if OR=='' and ins==0 and reg==0 and trans=='': return 'False1' if OR!='' and ins==0 and trans!='': return 'True1',rrr if OR!='' and ins!=0 and trans!='': return 'True2',rrr else: return 'False2'
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(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 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): # 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 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 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 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 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 revString(astring): s = Stack() #create a new stack for ch in astring: s.push(ch) reverse_string = '' for i in range(len(astring)): reverse_string = reverse_string + s.pop() return reverse_string
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 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 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 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 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 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 = '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 chkDate_allRec(self,m,a,camp): # que = "SELECT * FROM wp_2015ptainsuracelist where frm_time_date='%s';" % (a) # rr=m.db.query(que) dateData = (str(a),) que = """SELECT * FROM """+self.table+""" where frm_time_date==?""" rr=m.dbsql3.data_query(que,dateData,False) # print(rr) y = Stack() p= [] str2=[] if rr: for i in rr: print(i) # OR = i[18] # ins = i[16] # reg = i[15] # trans = i[19] # if i[18]!='' and i[15]!=0 and i[16]!=0 and i[19]!='' and i[20]==camp: y.push(list(i)) #Has a sibling and paid the insurance fee if i[18]!='' and i[15]==0 and i[16]!=0 and i[19]!='' and i[20]==camp: y.push(list(i)) #declared but not insured if i[18]!='' and i[15]==0 and i[16]==0 and i[19]!='' and i[20]==camp: y.push(list(i)) return True,y.seek() # ns!='': # return 'True2',rrr else: return False
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
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 moveTower(height,fromPole, toPole, withPole): fromPole = Stack() toPole = Stack() withPole = Stack() for i in range(height): fromPole.push(i) if fromPole.size() == 1: Disk = fromPole.pop() toPole.push(Disk) else: moveTower(height-1, fromPole, toPole, withPole) print fromPole, toPole, withPole
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 postfixEval(self, tokens): operandStack = Stack() for i in tokens: if i.isdigit(): operandStack.push(int(i)) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = self.compute(operand1, operand2, i) operandStack.push(result) return operandStack.pop()
def sortstacks(astack): temp=Stack() while not astack.isEmpty(): tmp=astack.pop() while temp.peek()<tmp: temp.pop() temp.push(tmp) return temp
def postfixEval(postfixExpr): operandStack = Stack() tokenList = postfixExpr.split() for token in tokenList: if token in '0123456789': operandStack.push(int(token)) elif token in '*/+-': num2 = operandStack.pop() num1 = operandStack.pop() operandStack.push(doMath(num1, num2, token)) return operandStack.pop()
def evalPostfix(postfixExpr): operandStack = Stack() tokenList = postfixExpr.split() prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1} for token in tokenList: if token.isdigit(): operandStack.push(int(token)) elif token in prec: op2 = operandStack.pop() op1 = operandStack.pop() res = doMath(token, op1, op2) operandStack.push(res) return operandStack.pop()
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 balance_parens(infix_string): valid_ops = ["+", "-", "*", "/"] opstack = Stack() output = list() infix_string = infix_string.split() for char in infix_string: if char == "(": opstack.push(char) elif char == ")": opstack.pop() elif char in valid_ops: opstack.append(char) return output
def eval_postfix(postfixExpr): operand_stack = Stack() tokenList = postfixExpr.split() for token in tokenList: # If the token is an operand, convert it from a string to an integer and push the value onto stack if token in "0123456789": operand_stack.push(int(token)) # If the token is an operator, *, /, +, or -, Pop the operandStack twice. else: operand2 = operand_stack.pop() operand1 = operand_stack.pop() # Perform the arithmetic operation. result = evaluate(token,operand1,operand2) # Push the result back on the stack. operand_stack.push(result)
# -*- coding:utf-8 -*- from pythonds.basic.stack import Stack """ Stack() 创建一个空的新栈。 它不需要参数,并返回一个空栈。 push(item)将一个新项添加到栈的顶部。它需要 item 做参数并不返回任何内容。 pop() 从栈中删除顶部项。它不需要参数并返回 item 。栈被修改。 peek() 从栈返回顶部项,但不会删除它。不需要参数。 不修改栈。 isEmpty() 测试栈是否为空。不需要参数,并返回布尔值。 size() 返回栈中的 item 数量。不需要参数,并返回一个整数。 """ # s = Stack() # print s.isEmpty() # s.push(8) # print s.isEmpty() # print s.size() # s.push(9) # print s.size() # print s.peek() # print(s.items) def firs_example(): """ 实现一个 mergeArray 函数,对两个已经排好序(从小到大)的数组进行排序(从小到大),数组里面是数字均为整数, 在 [0,100000) 之间,数组长度不超过 10000 。 输入数据有三行,第一行两个数字表示每个数组数字个数,后面两行分别表示两个数组 5,3 9,6,5,3,1 7,4,2
#stack frams: implmenting recursion from pythonds.basic.stack import Stack r_stack = Stack() def to_str(n, base): convert_string = "0123456789ABCDEF" while n > 0: if n < base: r_stack.push(convert_string[n]) else: r_stack.push(convert_string[n % base]) res = " " while not r_stack.isEmpty(): res = res + str(r_stack.pop()) return res print(to_str(1453, 16))
def xiaoxiaole(s): st = Stack() for a in s: if not st.isEmpty() and a == st.peek(): st.pop() else: st.push(a) if st.isEmpty(): return None else: output = '' while not st.isEmpty(): output = output + str(st.pop()) o = output[::-1] return o
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(infixexp): pres = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} openStack = Stack() postfixList = [] tokenList = infixexp.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "012346789": postfixList.append(token) elif token == "(": openStack.push(token) elif token == ")": topToken = openStack.pop() while token != "(": postfixList.append(topToken) topToken = openStack.pop() else: while (not openStack.isEmpty()) and (pres[openStack.peek()] >= pres[token]): postfixList.append(openStack.pop()) openStack.push(token) while not openStack.isEmpty(): postfixList.append(openStack.pop()) return " ".join(postfixList)
from pythonds.basic.stack import Stack def g(st, idx): if idx == len(st)-1: return int(st[idx]) * 2**0*1 else: n = len(st)-1 print(n) return g(st, idx+1) + (2**(n-idx)) * (int(st[idx])) rStack = Stack() def toStr(n,base): convertString = "0123456789ABCDEF" 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 + str(rStack.pop()) return res print(toStr(1453,16)) print('g:' + str(g('1101', 0)))
def parChecker(symbolString): s = Stack()
""" Draw a call stack for the Tower of Hanoi problem. Assume that you start with a stack of three disks. 缺陷:不能显示栈的内容 只能显示数目 改进:可用list模拟栈 """ from pythonds.basic.stack import Stack #print('请输入汉诺塔的层数') #N = int(input()) N = 3 global A, B, C, step A = Stack() B = Stack() C = Stack() x = [] step = 0 lst = list(range(1, N + 1)) lst.reverse() for i in lst: A.push(i) print(A.size()) def tower(s1, s2, s3, N=-1): # 汉诺塔算法,借助s2,将s1的N层移动到s3 global step if (N == -1): N = s1.size() if (N == 0): return elif (N == 1): # 判断栈的深度,如果栈深为1,则一次简单移动即可;若大于1,则需要进行递归操作
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 infix_to_prefix(infix_expr): prec = dict() prec[")"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 prefix_expr = [] s = Stack() # 从右到左扫描 for item in reversed(infix_expr.split()): # 如果标记是操作数,将其附加到输出列表的末尾 if item not in prec.keys(): prefix_expr.append(item) # 如果标记是右括号,将其压到 s 上 elif item == ')': s.push(item) # 如果标记是左括号,则弹出 s,直到删除相应的右括号。将每个运算符附加到 # 输出列表的末尾 elif item == '(': while s.peek() != ')': prefix_expr.append(s.pop()) s.pop() # 如果标记是运算符, *,/,+ 或 - ,将其压入 s。但是,首先删除已经在 # s 中具有更高或相等优先级的任何运算符,并将它们加到输出列表中 else: while (not s.is_empty()) \ and s.peek() != ')' \ and prec[s.peek()] > prec[item]: prefix_expr.append(s.pop()) s.push(item) s.push(item) # print(s.items) # 当输入表达式被完全处理时,检查 s。仍然在栈上的任何运算符都可以删除并加到 # 输出列表的末尾 while not s.is_empty(): prefix_expr.append(s.pop()) # 反转序列 prefix_expr.reverse() return ' '.join(prefix_expr)
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 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
# myScreen = turtle.Screen() # t.left(90) # t.up() # t.backward(100) # t.down() # t.color("red") # tree(75,t) # myScreen.exitonclick() # main() from pythonds.basic.stack import Stack def moveTower(height, fromPole, toPole, withPole): if height >= 1: moveTower(height - 1, fromPole, withPole, toPole) moveDisk(fromPole, toPole) moveTower(height - 1, withPole, toPole, fromPole) def moveDisk(fp, tp): print("移动盘子,从", fp, "到", tp) fromPole = Stack() toPole = Stack() withPole = Stack() moveTower(5, fromPole, toPole, withPole)
def mid2post(exp): expList = exp.split(' ') s = Stack() postList = [] for v in expList: if v == '(': s.push(v) elif v == ')': top = s.pop() while top != '(': postList.append(top) top = s.pop() elif v in '+-*\\': while not s.isEmpty() and priority(v) <= priority(s.peek()): top = s.pop() postList.append(top) s.push(v) else: postList.append(v) while not s.isEmpty(): postList.append(s.pop()) return ' '.join(postList)
def dailyTemp(T): ans_list = [] s = Stack() while abs(i) < len(T): if s.isEmpty() is True: s.push(i) ans_list[i] = 0 i = i - 1 else: if T[i] >= s.peek(): s.pop() i = i - 1 else: ans_list[i] = s.top() - i s.push(i) i = i - 1 return ans_list
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 push(self, item): # self.items.append(item) # # # 出栈 # def pop(self): # return self.items.pop() # # # 返回栈顶元素 # def peek(self): # return self.items[len(self.items)-1] # # # 返回栈的大小 # def size(self): # return len(self.items) if __name__ == '__main__': from pythonds.basic.stack import Stack s = Stack() s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size())
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
__author__ = 'bhavtosh' import unittest import parse from pythonds.basic.stack import Stack from pythonds.trees.binaryTree import BinaryTree fpexp = '( ( ( ( A & B ) | C ) | D ) & E ) ' #def buildParseTree(fpexp): fplist = fpexp.split() print "## fplist is: ", fplist pStack = Stack() print "## pStack is: ", pStack eTree = BinaryTree('') print "## eTree is: ", eTree pStack.push(eTree) print "## pStack.items is: ", pStack.items currentTree = eTree print "## currentTree is: ", currentTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['&', '|', '&~', '|~', ')']: currentTree.setRootVal(i) parent = pStack.pop()
def isValidConditions(conditions_string, selected_tables): global error #load tables column_list = list() loadSchema("ALL_TABLES", False, column_list) #---------------------------------------------------- global error isValid = False state = 0 pStack = Stack() eTree = BinaryTree("!") pStack.push(eTree) currentTree = eTree ctr = 0 operatorList = ["=", "AND", "OR"] lexer = shlex.shlex(conditions_string, posix=True) #lexer.whitespace += ';' lexer_list = list(lexer) print "\n[isValidConditions][lexer_list]:" print lexer_list #print "\n[isValidColumns][selected_tables]:" #print selected_tables #lexer_list = shlex.split(conditions_string) for i in range(0, len(lexer_list)): ctr += 1 #----------- term = lexer_list[i].upper() if term == "(": currentTree.insertLeft("") pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif (term not in operatorList) and (term not in ["(", ")", ";"]): # Check if term is a valid column or value if state == 0: result = next((i for i, v in enumerate(selected_tables) if v[0].upper() == term), -1) if result != -1: source_table_index = result state = 1 else: if isValidTerm(term): rootVal = term state = 99 else: error += "\n[ERROR] Expected a valid number or column name" return False elif state == 1: if term == ".": state = 2 else: error += "\n[ERROR] Expected '.'" return False elif state == 2: result = next((i for i, v in enumerate(column_list) if ( (v[0].upper() == selected_tables[source_table_index][1]) and (v[1].upper() == term))), -1) if result != -1: rootVal = column_list[result][0] + "." + column_list[ result][1] state = 99 else: error += "\n[ERROR] Expected a valid column name : " + str( term) return False if state == 99: if not pStack.isEmpty(): state = 0 currentTree.setRootVal(rootVal) parent = pStack.pop() currentTree = parent else: error += "\n[ERROR] Unbalanced operations" return False elif term in operatorList: currentTree.setRootVal(term) currentTree.insertRight("") pStack.push(currentTree) currentTree = currentTree.getRightChild() elif term == ")": if not pStack.isEmpty(): currentTree = pStack.pop() else: error += "\n[ERROR] Unbalanced operations" return False #elif term == ";": # i = len(lexer_list) + 1 else: raise ValueError if ctr > 0: if not pStack.isEmpty(): error += "\n[ERROR] Unbalanced grouping" return False else: return True else: return True
def xiaoxiaole(string): s = Stack() for index in range(len(string)): a = string[index] if s.isEmpty() or index == 0: s.push(a) else: if a != s.peek(): s.push(a) else: s.pop() if s.isEmpty(): return None else: output = '' while not s.isEmpty(): output = output + str(s.pop()) o = output[::-1] return o
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)
# 967 => 769 栈 后进先出 ------------- 底 967 顶 ------------- 可以用栈的方式实现递归 ''' from pythonds.basic.stack import Stack s = Stack() def to_str(num, base): convert_str = '0123456789ABCDEF' while num > 0: if num < base: s.push(convert_str[num]) else: s.push(convert_str[num % base]) num = num // base result = "" while not s.isEmpty():
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree i = 0 while (i < len(fplist)): #print("Analyzing:",fplist[i]) if fplist[i] == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif fplist[i] in ['|', '.']: currentTree.setRootVal(Nodo(fplist[i])) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif fplist[i] in ["*>", "+>"]: #if fplist[i+1] == '>': currentTree.setRootVal(Nodo(fplist[i])) currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() #i+=2 #continue elif fplist[i] in ['<*', '<+']: #if fplist[i+1] == '*': currentTree = pStack.pop() #i+=2 #continue elif fplist[i] not in ['.', '|', '*>', '+', ')', '<*']: currentTree.setRootVal(Nodo(fplist[i])) parent = pStack.pop() currentTree = parent elif fplist[i] == ')': currentTree = pStack.pop() else: raise ValueError if currentTree.getLeftChild( ) is not None and currentTree.getRightChild() is not None: currentTree = pStack.pop() i += 1 #return eTree return currentTree
def infix2postfix(infixexpr): """ 栈的使用:算术表达式中缀表达式转后缀表达式 :param infixexpr: 完全括号算术表达式 :return: 后缀表达式 """ prec = dict() prec['*'] = 3 prec['/'] = 3 prec['+'] = 2 prec['-'] = 2 prec['('] = 1 op_stack = Stack() postfix_list = [] token_list = infixexpr.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(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 postFixEvaluator(postfixexpr): aList = postfixexpr.split() aStack = Stack() for val in aList: if val == '+': num1 = int(aStack.pop()) num2 = int(aStack.pop()) aStack.push(num2 + num1) elif val == '-': num1 = int(aStack.pop()) num2 = int(aStack.pop()) aStack.push(num2 - num1) elif val == '*': num1 = int(aStack.pop()) num2 = int(aStack.pop()) aStack.push(num2 * num1) elif val == '/': num1 = int(aStack.pop()) num2 = int(aStack.pop()) aStack.push(int(num2 / num1)) else: aStack.push(val) return aStack.pop()
from pythonds.basic.stack import Stack from pythonds.trees.binaryTree import BinaryTree as ArbolBinario regex = input("Dame la regex:\n") #regex = "("+regex+").#" simbolos = "abcdefghijklmnopqrstuvxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#" b = 0 pila1 = Stack() pila2 = Stack() flag = True def buscaPivote(regex): if len(regex) == 1: return Nodo print(regex) pilas = [] pivotes = { '*' : 2, '+' : 2, '.' : 3, '|' : 4 }
def __init__(self): self.inbox = Stack() self.outbox = Stack()
from pythonds.basic.stack import Stack import random import string exp = '( ( ( a + null ) | b ) . c )' Parent = Stack() Ch = Stack() Operator = Stack() def Convert(exp): ListExp = exp.split() Production = {} NonTerminals = list(string.ascii_uppercase) for i in ListExp: if i == '(': Parent.push('(') elif i == ')': Parent.pop() op = Operator.pop() right = Ch.pop() left = Ch.pop() if Parent.isEmpty(): NT = 'S' del NonTerminals[NonTerminals.index('S')]