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 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 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 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 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 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 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 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 sortstacks(astack): temp=Stack() while not astack.isEmpty(): tmp=astack.pop() while temp.peek()<tmp: temp.pop() temp.push(tmp) return temp
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 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 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 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 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()
class Environment(object): def __init__(self, args): self.args = args self.path_pattern = re.compile("^(.)*\.py$") self.put_pattern = re.compile("^put ([0-9])+$") self.stack = Stack() def count(self): for arg in self.args: if (self.put_pattern.match(arg)): number = int(arg[4:]) self.stack.push(number) elif (arg == 'add'): number_1 = self.stack.pop() number_2 = self.stack.pop() result = number_1 + number_2 self.stack.push(result) elif (arg == 'sub'): number_1 = self.stack.pop() number_2 = self.stack.pop() result = number_2 - number_1 self.stack.push(result) elif (arg == 'mul'): number_1 = self.stack.pop() number_2 = self.stack.pop() result = number_1 * number_2 self.stack.push(result) elif (arg == 'div'): number_1 = self.stack.pop() number_2 = self.stack.pop() result = number_2 / number_1 self.stack.push(result) elif (arg == 'end'): return self.stack.pop() elif (self.path_pattern.match(arg)): pass else: #jakies rzucanie wyjatkiem print 'I got some strange input here: %s' % arg
def postfixEval(postfixExpr): operandStack = Stack() #create a new stack tokenList = postfixExpr.split() #split the expression by space 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 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)
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 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 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 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 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(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 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 build_parse_tree(fpexp): fplist = fpexp.split() for i in fplist: if i.__contains__('(') and i != '(': index = fplist.index(i) i_l = i.split('(') fplist[index] = i_l[-1] for j in range(len(i_l)-1): fplist.insert(index, '(') if i.__contains__(')') and i != ')': index = fplist.index(i) i_l = i.split(')') fplist[index] = i.split(')')[0] for j in range(len(i_l)-1): fplist.insert(index+1, ')') pstack = Stack() current_tree = BinaryTree('') current_tree.insertLeft('') pstack.push(current_tree) current_tree = current_tree.getLeftChild() for i in fplist: if i == '(': current_tree.insertLeft('') pstack.push(current_tree) current_tree = current_tree.getLeftChild() elif i not in ['and', 'or', ')']: current_tree.setRootVal(i) parent = pstack.pop() current_tree = parent elif i in ['and', 'or']: if current_tree.getRootVal() != "": pstack.push(current_tree) current_tree = BinaryTree('') current_tree.leftChild = pstack.pop() current_tree.setRootVal(i) current_tree.insertRight('') pstack.push(current_tree) current_tree = current_tree.getRightChild() elif i == ')': current_tree = pstack.pop() else: raise ValueError return current_tree
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 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 = binstring + digits[remstack.pop()] return binstring
class Queue: def __init__(self): # self.items = [] self.inbox = Stack() self.outbox = Stack() def enqueue(self, item): self.inbox.push(item) def dequeue(self): assert (self.outbox.isEmpty()) while not self.inbox.isEmpty(): self.outbox.push(self.inbox.pop()) res = self.outbox.pop() while not self.outbox.isEmpty(): self.inbox.push(self.outbox.pop()) return res def isEmpty(self): return self.size() == 0 def size(self): return self.inbox.size()
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()
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 divide_by_2(dec_number): rem_stack = Stack() while dec_number > 0: remainder = dec_number % 2 rem_stack.push(remainder) dec_number = dec_number // 2 bin_string = "" while not rem_stack.isEmpty(): bin_string = bin_string + str(rem_stack.pop()) return bin_string
def infixtoPostfix(infixexpr): prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1} opstack = Stack() postfixlist = [] tokenlist = [num for num in 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 divide_by_two(number): s = Stack() while number > 0 : remainder = number % 2 s.push(remainder) number = number // 2 size = s.size() result = "" for item in range(size): result += str(s.pop()) return result
def postfixEval(postfixExpr): operandStack = Stack() tokenList = postfixExpr.split() with io.open('diccionario.json', encoding='utf8') as f: data = json.load(f) docIDs = set() for token in tokenList: if (token != "*" and token != "/" and token != "+" and token != "-"): for indice in data['indexes']: if (indice['index'] == token): aux = indice['documents'] for doc in aux: docIDs.add(doc[0]) break operandStack.push(docIDs) docIDs = set() else: set2 = operandStack.pop() set1 = operandStack.pop() result = doMath(token, set1, set2) operandStack.push(result) return operandStack.pop()
def main(argv): windowName = "" clickCount = 10 sleepSec = 2 try: opts, args = getopt.getopt(argv, "hw:c:s:", ["window=", "clickcount=", "sleep="]) except getopt.GetoptError: print 'PyWinMonkey.py -w <Window Name> -c <Click Count=10> -s <Sleep Seconds Before Start=2>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'PyWinMonkey.py -w <Window Name> -c <Click Count=10> -s <Sleep Seconds Before Start>' sys.exit() elif opt in ("-w", "--window"): windowName = arg elif opt in ("-c", "--clickcount"): clickCount = int(arg) elif opt in ("-s", "--sleep"): sleepSec = int(arg) print(windowName + ", " + str(clickCount) + ", " + str(sleepSec)) if windowName == "": print("Error: Window name not found...") time.sleep(sleepSec) from pythonds.basic.stack import Stack s = Stack() win32gui.EnumWindows(callback, s) win_x = -1 win_y = -1 win_width = -1 win_height = -1 while s.size() > 0: win = s.pop() if win[4] == windowName: win_x = win[0] win_y = win[1] win_width = win[2] win_height = win[3] # print ("window status: "+str(win)) break if win_x > -1 and win_y > -1: for i in xrange(int(clickCount)): print(str(i)) xposition = random.randint(win_x + 10, win_x + win_width - 10) yposition = random.randint(win_y + 10, win_y + win_height - 10) print(str(xposition) + "," + str(yposition)) pyautogui.click(xposition, yposition)
def divideBy(decNumber, n): digits = '0123456789ABCDEF' remstack = Stack() while decNumber > 0: rem = decNumber % n #take the remainder remstack.push(rem) decNumber = decNumber // n # interger division binString = "" while not remstack.isEmpty(): binString = binString + digits[remstack.pop()] #the number is the place return binString
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)
def convBin(num): s = Stack() ii = 0 mystr = '' if num % 1 != 0: raise RuntimeError("Integer please") else: while num != 0: ii = num % 2 s.push(ii) num = num // 2 while not s.isEmpty(): mystr = mystr + str(s.pop()) return mystr
def divideBase(desNumber, base): digits = '0123456789ABCDEF' s = Stack() while desNumber > 0: rem = desNumber % base s.push(rem) desNumber = desNumber // base binString = "" while not s.isEmpty(): binString = binString + digits[s.pop()] return binString
def decToHex(dec): s = Stack() digits = '0123456789ABCDEF' while dec > 0: a = dec % 16 s.push(a) dec = dec // 16 binary = '' while not s.isEmpty(): binary = binary + digits[s.pop()] return binary
def baseConverter(number, base): digits = "0123456789ABCDEF" stack = Stack() result = '' while number > 0: remainder = number % base stack.push(remainder) number = number // base print(number) while not stack.isEmpty(): num = stack.pop() result = result + digits[num] return result
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 prefix_eval(prefix_expr): s = Stack() for item in reversed(prefix_expr.split()): # 如果不是运算符号,压栈 if item not in '+-*/': s.push(item) else: op1 = int(s.pop()) op2 = int(s.pop()) # print(op1, item, op2) result = do_match(item, op1, op2) s.push(result) # print(s.items) return result
def par_checker_one(symbolstring): """ 单个'('检验 :param symbolstring: :return: """ s = Stack() balance = True index = 0 while index < len(symbolstring) and balance: symbol = symbolstring[index] if symbol == '(': s.push(symbol) else: if s.isEmpty(): balance = False else: s.pop() index += 1 if balance and s.isEmpty(): return True else: return False
def parChecker(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol == "(": s.push(symbol) else: if s.isEmpty(): balanced = False else: s.pop() index = index + 1 if balanced and s.isEmpty(): return True else: return False
def eval(mystr): ops = "+-*/" mystr = mystr.split() s = Stack() for ii in mystr: print(ii) if ii in ops: jj = int(s.pop()) kk = int(s.pop()) if ii == "+": s.push(jj + kk) elif ii == "-": s.push(jj - kk) elif ii == "*": s.push(jj * kk) elif ii == "/": s.push(kk / jj) elif ii == "**": s.push(kk**ii) else: s.push(ii) return (s.pop())
def base_converter(dec_number, base): '''This is a function that takes any decimal number and converts it according to the specified base''' digits = '0123456789ABCDEF' rem_stack = Stack() while dec_number > 0: rem = dec_number % base rem_stack.push(rem) dec_number = dec_number // base new_string = '' while not rem_stack.isEmpty(): new_string = new_string + digits[rem_stack.pop()] return new_string
def parCheck(symbolsting):#假设symbolsting是"(())" s=Stack() flag=True index=0 while index<len(symbolsting)and flag: symbol = symbolsting[index] if symbol=="(": s.push(symbol)#入栈 else: if s.isEmpty():#isEmpty()测试栈是否为空。不需要参数,返回布尔值 flag=False else: s.pop()#pop()从栈中删除顶部项。它不需要参数并返回item。栈被修改 index=index+1 if flag and s.isEmpty(): return True else: return False
def divideBy2(decNumber): remstack = Stack() while decNumber > 0: rem = decNumber % 2 # use modulo '%' to get the remainder, eg rem = 8%3 = 2 remstack.push( rem) # get the floor of divide operation, eg ans= 8//3 = 2 decNumber = decNumber // 2 # therefore, ans*3 + rem = decNumber binString = "" while not remstack.isEmpty(): binString = binString + str(remstack.pop()) return binString
def base_converter(decimal: int, base: int) -> str: digits = "0123456789ABCDEF" stack = Stack() while decimal > 0: remainder = decimal % base stack.push(remainder) decimal = decimal // base ans = "" while not stack.isEmpty(): ans += digits[stack.pop()] return ans
def divideBy2(decNumber): remStack = Stack() while decNumber > 0: rem = decNumber % 2 remStack.push(rem) decNumber = decNumber // 2 binString = "" while not remStack.isEmpty(): binString += str(remStack.pop()) return binString
def divideBy2(num): st = Stack() while num > 0: rem = num % 2 st.push(rem) num = num // 2 binStr = "" while not st.isEmpty(): binStr += str(st.pop()) return binStr
def infixToPostfix(infixexpr): prec = {} prec["*"] = 5 prec["/"] = 5 prec["+"] = 4 prec["-"] = 4 prec["("] = 3 prec[">="] = 2 prec["=="] = 2 prec["<="] = 2 prec["and"] = 1 prec['or'] = 1 prec["="] = 0 opStack = Stack() postfixList = [] tokenList = infixexpr.split() print tokenList for token in tokenList: if token[0] in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" or token in '0123456789': postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList)
def buildParseTree(fpexp): fplist = fpexp.split() # create a list by splitting the space pStack = Stack() # create a stack eTree = BinaryTree('') # create a tree pStack.push(eTree) # push the top node currentTree = eTree # current node as node at the top of the tree for i in fplist: if i == '(': # if '(': push it down to the left child node currentTree.insertLeft('') # insert a left child pStack.push(currentTree) currentTree = currentTree.getLeftChild( ) # move it down to the left child node elif i in ['+', '-', '*', '/']: # if it's a operator currentTree.setRootVal( i) # set the root value of the current node to the operator currentTree.insertRight('') # add a new right child pStack.push(currentTree) # add currentTree to the stack currentTree = currentTree.getRightChild( ) # move to the right child node elif i == ')': currentTree = pStack.pop() # go to the parent of the current node elif i not in ['+', '-', '*', '/', ')']: # if it's a number try: currentTree.setRootVal( int(i) ) # set root value of the current node to the number (int(i)) parent = pStack.pop() # set the parent currentTree = parent # return to the parent except ValueError: raise ValueError("token '{}' is not a valid integer".format(i)) return eTree
def ParseTree(exp): listCh = exp.split() ChStack = Stack() expTree = BinaryTree('') ChStack.push(expTree) currentTree = expTree for i in listCh: if i == '(': currentTree.insertLeft('') ChStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i == ')': currentTree = ChStack.pop() elif i in ['*', '+', '|', '.']: if i not in ['*', '+']: currentTree.setRootVal(i) currentTree.insertRight('') ChStack.push(currentTree) currentTree = currentTree.getRightChild() else: currentTree.setRootVal(i) currentTree.insertRight('') currentTree.getRightChild().setRootVal('null') elif i not in ['*', '+', '|', '.']: try: currentTree.setRootVal(i) parent = ChStack.pop() currentTree = parent except ValueError: pass return expTree