def minimum_bracket_reversals(input_string): """ Calculate the number of reversals to fix the brackets Args: input_string(string): Strings to be used for bracket reversal calculation Returns: int: Number of breacket reversals needed """ if len(input_string) % 2 == 1: return -1 stack = Stack() count = 0 for bracket in input_string: if stack.is_empty(): stack.push(bracket) else: top = stack.top() if top != bracket: if top == "{": stack.pop() stack.push(bracket) while not stack.is_empty(): first = stack.pop() second = stack.pop() if first == "}" and second == "}": count += 1 elif first == '{' and second == '}': count += 2 elif first == '{' and second == '{': count += 1 return count
def main(fichier): s=stack.create() ind_char=stack.create() ind_ligne=stack.create() nb_ligne=0 in_channel = open(fichier, 'r') chaine="debut" while(chaine != ''): chaine=in_channel.readline() nb_ligne=nb_ligne+1 for i in range(len(chaine)): if(chaine[i]=="(" or chaine[i]=="[" or chaine[i]=="{") : stack.push(chaine[i],s) stack.push(i,ind_char) stack.push(nb_ligne,ind_ligne) elif(chaine[i]==")" or chaine[i]=="]" or chaine[i]=="}"): if(not (stack.is_empty(s))): if (stack.top(s)==getOpening(chaine[i])): stack.pop(s) else: print("Closed parenthese",chaine[i]," at line ",nb_ligne," char ",i," don't match the open parenthese ",stack.top(s)," at line ",stack.top(ind_ligne)," char ",stack.top(ind_char)) else: print("No open parenthese matching parenthese ",chaine[i]," at line ",nb_ligne," char ",i) chaine=in_channel.readline() if(not stack.is_empty(s)): print("Parenthese ",stack.top(s)," at line ",stack.top(nb_ligne)," char ",stack.top(nb_char)," has no matching closed parenthese.")
def postfix_notation(E:list): """Вычисляет выражение в постфиксной нотации(обратной польской нотации). >>> E = ['2', '7', '5', '*', '+'] >>> postfix_notation(E) == 2 + 7 * 5 True >>> E = ['2','5', '+', '7', '*'] >>> postfix_notation(E) == (2 + 5) * 7 True """ for element in E: if element.isdigit(): stack.push(element) else: x = int(stack.pop()) y = int(stack.pop()) if element == '+': z = y + x elif element == '-': z = y - x elif element == '*': z = y * x else: z = y // x stack.push(z) result = stack.pop() return result
def body_outer(self, arr, ix, s, p, left, right, last): s1, p1, l = pop(s, p, length=self.length, default_value=-1) s2, p2, r = pop(s1, p1, length=self.length, default_value=-1) def inner_loop(arr, ix, s, p, left, right, last): _, _ix, _s, _p, _left, _right, _last = tf.while_loop( self.cond_inner, self.body_inner, [arr, ix, s, p, left, right, last]) _arr = tf.scatter_update(self.arr, [_left, _last], [self.arr[_last], self.arr[_left]]) s1, p1 = push(_s, _p, _last - 1, length=self.length) s2, p2 = push(s1, p1, _left, length=self.length) s3, p3 = push(s2, p2, _right, length=self.length) s4, p4 = push(s3, p3, _last + 1, length=self.length) return _arr, ix, s4, p4, _left, _right, _last def fn(arr, ix, s, p, left, right, last): last = left ix = left + 1 return inner_loop(arr, ix, s, p, left, right, last) return tf.cond(tf.greater_equal(l, r), lambda: (arr, ix, s2, p2, l, r, last), lambda: fn(arr, ix, s2, p2, l, r, last))
def test_stack_ops(self): """ -- Verifica que el ultimo elemento ingresado en la cola sea el primero en salir """ L = LinkedList() push(L, "hola") push(L, "jorge") push(L, "como") push(L, "va?") first = pop(L) second = pop(L) self.assertEqual([first, second], ["va?", "como"])
def getValues(valueStack, inputStack, opStack): stack.pop(inputStack) # This is the operation z = stack.pop(opStack) # This is the first value A = stack.pop(valueStack) A = float(A) # This is the second value B = stack.pop(valueStack) B = float(B) newValue = findValue(B, z, A) return newValue
def findMaximums(self, nums): res = [0] * len(nums) nums += [-1 * sys.maxint] stack = [-1] for i in xrange(len(nums)): while nums[i] < (nums[stack[-1]] if stack[-1] >= 0 else -1 * sys.maxint): res[i - stack[-2] - 2] = max(res[i - stack[-2] - 2], nums[stack[-1]]) stack.pop() stack.append(i) for i in reversed(xrange(len(nums) - 2)): res[i] = max(res[i + 1], res[i]) return res
def run(splexems): stack.clear() for i in splexems: if type(i) is float: stack.push(float(i)) elif i in '+-*/^%': a = stack.pop() b = stack.pop() if i == '+': stack.push(b + a) elif i == '-': stack.push(b - a) elif i == '*': stack.push(a * b) elif i == '/': stack.push(b / a) elif i == '%': stack.push(b * a / 100) else: stack.push(math.pow(b, a)) elif i == 'min': a = stack.pop() stack.push(unr(a)) elif i == '!': a = stack.pop() stack.push(factorial(a)) else: if funccountarg[i[1:]] == 1: a = stack.pop() stack.push(runfunc([i[1:]], a)) elif funccountarg[i[1:]] == 2: a = stack.pop() b = stack.pop() stack.push(run2func(i[1:], b, a)) else: stack.push(run0func(i[1:])) return stack.pop()
def bracket(str): dict = {'(':')','{':'}','[':']'} ouv = stack.create() fer = stack.create() for i in range(len(str)): if(str[i]=='(' or str[i]=='[' or str[i]=='{'): ouv+=[str[i]] elif(str[i]==")" or str[i]=="]" or str[i]=='}'): fer+=[str[i]] if(dict[stack.pop(ouv)]!=stack.pop(fer)): return False if(len(ouv)!=0 or len(fer)!=0): return False return True
def solve_puzzle(red, green, blue): """ Takes in three stacks and then sorts them based on ball color. First it checks each ball in the red can. If the ball is green it goes in green, if the ball is red or blue it goes in blue. Then it looks at the blue can. If the ball is red it goes in the red, if it is blue it goes in the green. Lastly all the blue balls in the green can move back to the blue can and the stacks of balls will be sorted. The function also tracks the amount of moves the sorting process takes and returns it. Pre-Conditions: It is assumed that all balls will begin in the red can and that the green and blue cans are empty. :param red: Red Can :param green: Green Can :param blue: Blue Can :return: moves """ moves = 0 stack_list = [red, green, blue] while stack.is_empty(red) != True: top_val = stack.top(red) if top_val == "R" or top_val == "B": stack.pop(red) stack.push(blue, top_val) animate.animate_move(stack_list, 0, 2) else: stack.pop(red) stack.push(green, top_val) animate.animate_move(stack_list, 0, 1) moves += 1 while stack.is_empty(blue) != True: top_val = stack.top(blue) if top_val == "R": stack.pop(blue) stack.push(red, top_val) animate.animate_move(stack_list, 2, 0) else: stack.pop(blue) stack.push(green, top_val) animate.animate_move(stack_list, 2, 1) moves += 1 while stack.top(green) != "G": top_val = stack.top(green) stack.pop(green) stack.push(blue, top_val) animate.animate_move(stack_list, 1, 2) moves += 1 return moves
def is_braces_sequenct_correct(seq: str) -> bool: """ Check correctness of braces sequence in statement >>> is_braces_sequenct_correct('() (())') True >>> is_braces_sequenct_correct('()[()]') True >>> is_braces_sequenct_correct(')') False >>> is_braces_sequenct_correct('[()') False >>> is_braces_sequenct_correct('[()])') False """ correspondent = dict(zip('([{', ')]}')) for brace in seq: if brace in '([{': stack.push(brace) continue elif brace in ')]}': if stack.is_empty(): return False left = stack.pop() if correspondent[left] != brace: return False return stack.is_empty()
def is_braces_sequences_correct(s): """ Проверяет корректность скобочной последовательности из куглых и квадратных скобок. >>> is_braces_sequences_correct('(([()]))[]') True >>> is_braces_sequences_correct('[(])') False >>> is_braces_sequences_correct('(') False >>> is_braces_sequences_correct(']') False """ braces = '()[]' for brace in s: if brace not in braces: continue if brace in '([': stack.push(brace) else: assert brace in ')]', 'Oups! I expect close brace: ' + str(brace) if stack.is_empty(): return False left = stack.pop() assert left in '([', 'Oups! I expect open brace: ' + str(brace) if left == "(": right = ")" if left == "[": right = "]" if right != brace: return False return stack.is_empty()
def is_braces_sequence_correct(seq: str) -> bool: """ Check correctness of braces sequence in statement >>> is_braces_sequence_correct("()(())") True >>> is_braces_sequence_correct("()[()]") True >>> is_braces_sequence_correct(")") False >>> is_braces_sequence_correct("[()") False >>> is_braces_sequence_correct("[(])") False """ correspondent = dict(zip("([{", ")]}")) for brace in seq: if brace in "([{": stack.push(brace) continue elif brace in ")]}": if stack.is_empty(): return False left = stack.pop() if correspondent[left] != brace: return False return stack.is_empty()
def is_braces_sequence_correct(s: str): """Проверяет является ли корректной скобочная последовательность, содержащая скобки вида: () []. >>> is_braces_sequence_correct("(([()]))[]") True >>> is_braces_sequence_correct("([)]") False >>> is_braces_sequence_correct("(") False >>> is_braces_sequence_correct("]") False """ for brace in s: if brace not in "[]()": continue if brace in "[(": stack.push(brace) else: assert brace in ")]", "Ожидалась закрывющая скобка, получена: " + str( brace) if stack.is_empty(): return False left = stack.pop() assert left in "([" "Ожидалась открывающая скобка, получена: " + str( brace) if left == "(": right = ")" else: right = "]" if brace != right: return False return stack.is_empty()
def DFS(graph, start): visited, s = [], stack.Stack() s.push(start) while s: node = stack.pop() if node.key not in visited: visited.add(node.key)
def is_breces_sequence_correct(s: str): """ checks the correctness of the breces sequence of parentheses and square brackets () [] >>> is_breces_sequence_correct("(([()]))[]") True >>> is_breces_sequence_correct("([)]") False >>> is_breces_sequence_correct("(") False >>> is_breces_sequence_correct("]") False """ for brace in s: if brace not in "()[]": continue if brace in "([": stack.push(brace) else: assert brace in ")]", "Closing braces expected: " + str(brace) if stack.is_empty(): return False left = stack.pop() assert left in "([", "Opening braces expected: " + str(brace) if left == "(": right = ")" elif left == "[": right = "]" if right != brace: return False return stack.is_empty()
def findMaximums(self, nums: List[int]) -> List[int]: N = len(nums) cl = [None]*N cr = [None]*N stack = [] for i in range(N): while stack and nums[stack[-1]]>=nums[i]: stack.pop() if not stack: cl[i] = i+1 else: cl[i] = i-stack[-1] stack.append(i) # now cl[i]==a means that nums[i] is a minimum of the range of length a starting from i # and going to the left stack = [] for i in range(N-1,-1,-1): while stack and nums[stack[-1]]>=nums[i]: stack.pop() if not stack: cr[i] = N-i else: cr[i] = stack[-1]-i stack.append(i) # now cr[i]==b means that nums[i] is a minimum of the range of length b starting from i # and going to the right cnt = [a+b-1 for a,b in zip(cl,cr)] # cnt[i]==c means that there is a subarray of length c where nums[i] is a minimum # and c is the maximum possible one cnti = sorted(range(N), key=cnt.__getitem__, reverse=True) # reverse argsort ofs = 0 ans = [None]*N best = -10**10 for L in range(N,0,-1): # will fill ans[L-1] # ans[L-1] is the max of all such nums[i] that cnt[i]>=L while ofs<N and cnt[cnti[ofs]]>=L: best = max(best,nums[cnti[ofs]]) ofs += 1 ans[L-1] = best return ans
def verif_parentheses(chaine): s=stack.create() for i in range(len(chaine)): """ print(s) """ if(chaine[i]=="(" or chaine[i]=="[" or chaine[i]=="{") : stack.push(chaine[i],s) elif(chaine[i]==")" or chaine[i]=="]" or chaine[i]=="}"): if(not (stack.is_empty(s)) and stack.top(s)==getOpening(chaine[i])): stack.pop(s) else: return -1 if(stack.is_empty(s)): return 1 else: return 0
def validateEquation(valueStack, opStack): validChar = "+-*/%^(" topOp = stack.top(opStack) topValue = stack.top(valueStack) # Pop topValue stack.pop(valueStack) # This determines whether an equation can be solved or not if topOp in validChar: try: secValue = stack.top(valueStack) secValue = float(secValue) stack.push(valueStack, topValue) return True except ValueError: return False else: stack.push(valueStack, topValue) return True
def findMaximums(self, nums: List[int]) -> List[int]: stack, n = [], len(nums) ans = [0] * n for i, num in enumerate(nums): while stack and nums[stack[-1]] >= num: # ensure mono-increase min_idx = stack.pop() # min_idx is the `stack_top_idx` we mentioned earlier, smallest between `left` and `right` below left, right = (stack[-1] + 1) if stack else 0, i # left & right end of window, left is `second_stack_top_idx + 1`, right is `i` window = right - left - 1 # window_size_idx = window size - 1 ans[window] = max(ans[window], nums[min_idx]) # update maximum stack.append(i) else: while stack: # at the end of iteration, we want to pop out all elements in stack. Here assuming the `current_value` is super small, so that every number in the stack will be popped out min_idx = stack.pop() left, right = (stack[-1] + 1) if stack else 0, n window = right - left - 1 ans[window] = max(ans[window], nums[min_idx]) for i in range(n-2, -1, -1): # update non-touched windows using result for larger windows ans[i] = max(ans[i], ans[i+1]) return ans
def reverseString(stack, string): for character in string: stack.push(character) reversedString = "" while not stack.isEmpty(): reversedString += stack.pop() return reversedString
def preOrder(node): stack = stack.stack() stack.push(node) while not stack.empty(): top = stack.pop() print('{}'.format(top.data)) if top.right != None: stack.push(top.right) if top.left != None: stack.push(top.left)
def calculator(element, numbers): """ Calculator function that takes the first two numbers on the top of the stack and decides what type is the operand. """ a = int(stack.pop(numbers)) if not stack.isEmpty(numbers) else error() b = int(stack.pop(numbers)) if not stack.isEmpty(numbers) else error() #Checks operator's type if element == '+': result = plus(a,b) stack.push(numbers, result) elif element == '-': result = minus(a,b) stack.push(numbers, result) elif element == '*': result = multipl(a,b) stack.push(numbers, result) elif element == '/': result = division(a,b) stack.push(numbers, result)
def deliminate(cmd): op = cmd[0] if op == 'push': stack.push(num=int(cmd[1])) if op == 'pop': print(stack.pop()) if op == 'size': print(stack.size()) if op == 'empty': print(stack.empty()) if op == 'top': print(stack.top())
def calculator(element, numbers): """ Calculator function that takes the first two numbers on the top of the stack and decides what type is the operand. """ a = int(stack.pop(numbers)) if not stack.isEmpty(numbers) else error() b = int(stack.pop(numbers)) if not stack.isEmpty(numbers) else error() #Checks operator's type if element == '+': result = plus(a, b) stack.push(numbers, result) elif element == '-': result = minus(a, b) stack.push(numbers, result) elif element == '*': result = multipl(a, b) stack.push(numbers, result) elif element == '/': result = division(a, b) stack.push(numbers, result)
def inOrder(node): stack = stack.stack() stack.push(node) finished = False while not stack.empty(): top = stack.top() if finished: print('{}'.format(top.data)) stack.pop() if top.right != None: stack.push(top.right) finished = False elif top.left != None: stack.push(top.left) else: print('{}'.format(top.data)) if top.right != None: stack.push(top.right) finished = False else: finished = True # leaf stack.pop()
def findMaximums(self, nums: List[int]) -> List[int]: ans = [0]*len(nums) stack = [] for i, x in enumerate(nums + [0]): while stack and stack[-1][1] >= x: _, xx = stack.pop() k = i-stack[-1][0]-2 if stack else i-1 ans[k] = max(ans[k], xx) stack.append((i, x)) for i in reversed(range(len(nums)-1)): ans[i] = max(ans[i], ans[i+1]) return ans
def conv2hex(decD, dec_string): """ This will take in a decimal value in integer form and convert and return its hexadecimal value. """ value = dec_string new_stack = stack.getStack() while (value % 16) != 0: stack.push(new_stack, decD[value % 16]) value //= 16 final = '' while stack.isEmpty(new_stack) == False: final += str(stack.pop(new_stack)) return final
def stack_list(list, stack): ''' (list,Stack)--> NoneType Adds each element of the list to the stack. Removes the top element from the stack. If the element is a non-list, it prints it. If the element is a list, it stores each of its elements on the stack. Continue the previous step until the stack is empty. Check for an empty stack, rather than causing an exception to be raised! ''' for i in list: stack.push(i) while not stack.is_empty(): first = stack.pop() if not isinstance(first, list): print(first) else: stack_list(first, stack)
def ic(x: str): stack.clear() if x == '': return False for brace in x: if brace in '()': if brace in '(': stack.push(brace) else: if stack.is_empty(): return False left = stack.pop() if left == '(': right = ')' if brace != right: return False return stack.is_empty()
def main(): import stack mystack = stack.getStack() for item in range(1, 5): stack.push(mystack, item) print('Pushing', item, 'on stack') peek = stack.peek( mystack, (int(input('Enter an element you want to peek into the stack: ')))) if peek == True: print('Element is in stack') else: print('Element is not in stack') while not stack.isEmpty(mystack): item = stack.pop(mystack) print('Popping', item, 'from stack')
def translateLine(tokens, filename=''): error = False # Push or Pop if (tokens[0] in memoryOperators) and (tokens[2].isdigit()): if tokens[0] == 'push': return stack.push(tokens[1], tokens[2]), error else: str, err = stack.pop(tokens[1], tokens[2]) return str, (err or error) # Stack Arith elif (tokens[0] in operators) or (tokens[0] in logicalOperators): return operatorHandler(tokens[0]), error elif tokens[0] == 'label': return '(' + tokens[1] + ')\n' elif tokens[0] == 'goto': return '@' + tokens[1] + '\n0;JMP\n' elif tokens[0] == 'if-goto': return '@SP\nAM=M-1\nD=M\n@' + tokens[1] + '\nD;JNE\n' return '', True
def isvalid(s): opposite = {'(':')','{':'}','[':']'} tempstack = [] for i in s: if i in opposite.keys(): stack.push(i) tempstack = stack.getlist() if i in opposite.values(): if stack.isempty()==True: return(False) else: t = stack.pop() tempstack = stack.getlist() if opposite[t] != i: return(False) if stack.isempty()!=True: return(False) else: return(True)
def my_tree(aroot,args,result,stack=stack.Stack()): while True: items = os.listdir(aroot) for item in items: lis = collections.defaultdict(str) fullitem = os.path.join(aroot,item) if os.path.isdir(fullitem): if not item.startswith('.') or args.hidden: stack.push(fullitem) else: if args.hidden or not item.startswith('.'): lis['name'] =aroot + "/" + item if args.sizes or args.ordered == 'size' or args.ordered == 's': lis['size'] = os.path.getsize(fullitem) if args.modified or args.ordered == 'modified' or args.ordered == 'm': lis['modified'] = os.path.getmtime(fullitem) lis['root'] = aroot.lstrip(args.directory) result.append(lis) if stack.length()<1: return result else: aroot = stack.pop()
def dfs(maze, stack): length = len(maze) start = maze[0][0] goal = (9, 9) stack.push(start) while stack.isEmpty() == False: node = stack.pop() node.searched = True for x, y in (node.x + 1, node.y), (node.x - 1, node.y), (node.x, node.y - 1), (node.x, node.y + 1): if (0 <= x < length and 0 <= y < length) and ( maze[x][y].wall == False) and (maze[x][y].searched == False): if (x, y) == goal: return True else: maze[x][y].parent = node stack.push(maze[x][y]) return False
def palindromeChecker(s): """ Returns True if the provided string is a palindrome. Uses the stack Module (added in this directory) and the Let's Apply it section from the chapter. """ import stack # init char_stack = stack.getStack() while s != '': if len(s) == 1: return True else: # init is_palindrome = True # to handle strings of odd length compare_length = len(s) // 2 # push second half of input string on stack for k in range(compare_length, len(s)): stack.push(char_stack, s[k]) # pop chars and compare to first half of string k = 0 while k < compare_length and is_palindrome: ch = stack.pop(char_stack) if s[k].lower() != ch.lower(): is_palindrome = False k = k + 1 # return values if is_palindrome: return True else: return False
def postOrder(node): stack = stack.stack() stack.push(node) lastest = None while not stack.empty(): top = stack.top() if top.left == lastest and top.right == None: print('{}'.format(top.data)) lastest = top stack.pop() elif top.right == lastest: print('{}'.format(top.data)) lastest = top stack.pop() else: if top.right != None: stack.push(top.right) if top.left != None: stack.push(top.left) if top.left == None and top.right == None: print('{}'.format(top.data)) lastest = top stack.pop()
import stack """ Ask the user to enter a series of braces and parentheses, then indicate if they are properly nested """ char = input('Enter parentheses and/or braces: ') sequence = stack.getStack() #for every element in the received string checks the type and pushes/pops in/from the stack for el in char: if el == '(' or el == '{': stack.push(sequence, el) elif not stack.isEmpty(sequence): if el == ')' and stack.top(sequence) == '(': stack.pop(sequence) elif el == '}' and stack.top(sequence) == '{': stack.pop(sequence) #Final check if the stack is empty #If it's empty the string is proper if stack.isEmpty(sequence): print('Nested properly.') else: print('Not properly nested.')
result = multipl(a,b) stack.push(numbers, result) elif element == '/': result = division(a,b) stack.push(numbers, result) """ Main functionality of the program. Asks user to enter a sequence of operands and operators. Determines to which group it belongs and do the calculation. """ num = stack.getStack() while flag == True: exp = input('Enter an RPN expression: ') for el in exp: if el in operand: stack.push(num, el) elif el in operator: calculator(el, num) elif el == '=': print('Value of expression: ', int(stack.pop(num))) else: flag = False #Resets the stack num = stack.getStack()
def bracket(str): dict = {"(": ")", "{": "}", "[": "]"} ouv = stack.create() fer = stack.create() ouvLines = stack.create() ferLines = stack.create() ouvChars = stack.create() ferChars = stack.create() line = 1 char = 0 for i in range(len(str)): if str[i] == "\n": line += 1 char = 0 char += 1 if str[i] == "(" or str[i] == "[" or str[i] == "{": ouv += [str[i]] ouvLines += [line] ouvChars += [char] elif str[i] == ")" or str[i] == "]" or str[i] == "}": fer += [str[i]] ferLines += [line] ferChars += [char] if len(ouv) != 0: o = stack.pop(ouv) f = stack.pop(fer) ol = stack.pop(ouvLines) fl = stack.pop(ferLines) oc = stack.pop(ouvChars) fc = stack.pop(ferChars) else: f = stack.pop(fer) fl = stack.pop(ferLines) fc = stack.pop(ferChars) return ( "No open parenthese matching parenthese " + f + " at line " + builtins.str(fl) + " char " + builtins.str(fc) + "." ) if dict[o] != f: return ( "Closed parenthese " + f + " at line " + builtins.str(fl) + " char " + builtins.str(fc) + " don't match the open parenthese " + o + " at line " + builtins.str(ol) + " char " + builtins.str(oc) + "." ) if len(ouv) != 0 and len(fer) == 0: o = stack.pop(ouv) ol = stack.pop(ouvLines) oc = stack.pop(ouvChars) return ( "Parenthese " + o + " at line " + builtins.str(ol) + " char " + builtins.str(oc) + " has no matching closed parenthese." ) return "Well parenthesed."
def stackPush(listEquation, inputPriority, stackPriority): valueStack = stack.stack() opStack = stack.stack() inputStack = stack.stack() stack.push(valueStack, "$") stack.push(opStack, "$") stack.push(inputStack, -1) # To count the number of elements in the equation list count = 0 for i in listEquation: count += 1 print("Looking at", i, "in the equation") if i in "123456789": stack.push(valueStack, i) print("Adding", i, "to valueStack") elif i in "+-*/%^(": # This solves the part of the equation before this, until the new # input priority can be put in while inputPriority [i] <= stack.top(inputStack): print("STACK VALUE >= the new INPUT PRIORITY.", end = " ") print("So pop and process, and recheck.") newValue = getValues(valueStack, inputStack, opStack) newValue = float(newValue) print("New answer being placed into the VALUE", end = " ") print("stack is: ", newValue) stack.push(valueStack, newValue) stack.push(opStack, i) print(i, "was just added to opStack") stack.push(inputStack, stackPriority [i]) print(stackPriority [i], "was just added to inputStack") elif i == ")": print("Pop and process, found a )") while stack.top(opStack) != "(" and stack.top(opStack) != "$": newValue = getValues(valueStack, inputStack, opStack) newValue = float(newValue) print("New answer being placed into the VALUE", end = " ") print("stack is: ", newValue) stack.push(valueStack, newValue) # This makes sure that there is a '(' in the equation if stack.top(opStack) == "$": print("ERROR: unable to solve equation") return else: stack.pop(opStack) stack.pop(inputStack) if len(listEquation) == count: boolean = False # This determines if the equation has been solved or not if stack.top(valueStack) == "$" and stack.top(opStack) == "$": try: stack.push(valueStack, newValue) boolean = True except UnboundLocalError: print("ERROR: unable to solve equation") return while boolean == False: print("END OF EQUATION, so pop and process until", end = " ") print("opStack is only a '$'") topValue = stack.top(valueStack) # Solves for errors if stack.top(valueStack) == "$" and stack.top(opStack) != "$": print("ERROR: unable to solve equation") return stack.pop(valueStack) topValue = float(topValue) if stack.top(valueStack) == "$" and stack.top(opStack) == "$": print("The answer is ", topValue) return stack.push(valueStack, topValue) bool2 = validateEquation(valueStack, opStack) if bool2 == False: print("ERROR: unable to solve equation") return newValue = getValues(valueStack, inputStack, opStack) # Catches this error if newValue == "???": print("ERROR: unable to solve equation") return newValue = float(newValue) print("New answer being placed into the VALUE", end = " ") print("stack is: ", newValue) if stack.top(valueStack) == "$" and stack.top(opStack) == "$": stack.push(valueStack, newValue) boolean = True else: stack.push(valueStack, newValue) newValue = stack.pop(valueStack) print("The answer is ", float(newValue))
#creae an object stack = stack.Stack() #isEmpty() print stack.isEmpty() #display() stack.display() #push() for n in range(0,101,10): stack.push(n) #display() stack.display() #pop() for i in range(5): print "popped element", stack.pop() stack.display() #peek() print "top element = ", stack.peek() stack.display() print "popped element ", stack.pop() print "top element = ", stack.peek() stack.display()
RPN_list = RPN.split() state = "Progress" i = 0 num1 = 0 num2 = 0 result = 0 equal_flag = False # push the number to the stack while state == "Progress" and i < len(RPN_list): if RPN_list[i] == '+' or RPN_list[i] == '*' or RPN_list[ i] == '-' or RPN_list[i] == '/' or RPN_list[i] == '=': if RPN_list[i] == '=': equal_flag = True if len(RPN_stack) == 1 and i == len(RPN_list) - 1: result = float(stack.pop(RPN_stack)) else: state = "Error" else: if stack.isEmpty(RPN_stack) or len(RPN_stack) == 1: state = "Stack Underflow" break num2 = float(stack.pop(RPN_stack)) num1 = float(stack.pop(RPN_stack)) # evaluating the result if RPN_list[i] == '+': stack.push(RPN_stack, format(num1 + num2, '.2f')) elif RPN_list[i] == '*': stack.push(RPN_stack, format(num1 * num2, '.2f'))
def bracket(str): dict = {'(':')','{':'}','[':']'} ouv = stack.create() fer = stack.create() ouvLines = stack.create() ferLines = stack.create() ouvChars = stack.create() ferChars = stack.create() line = 1 char = 0 inComment = False inString = False for i in range(len(str)): if(inComment and str[i]!="\n"): continue elif(inComment and str[i]=="\n"): inComment = False if(str[i]=="\n"): line += 1 char = 0 if(str[i]=="#"): inComment = True char += 1 if(str[i]=='(' or str[i]=='[' or str[i]=='{'): ouv+=[str[i]] ouvLines+=[line] ouvChars+=[char] elif(str[i]==")" or str[i]=="]" or str[i]=='}'): fer+=[str[i]] ferLines+=[line] ferChars+=[char] if(len(ouv)!=0): o = stack.pop(ouv) f = stack.pop(fer) ol = stack.pop(ouvLines) fl = stack.pop(ferLines) oc = stack.pop(ouvChars) fc = stack.pop(ferChars) else: f = stack.pop(fer) fl = stack.pop(ferLines) fc = stack.pop(ferChars) return "No open parenthese matching parenthese "+f+" at line "+builtins.str(fl)+" char "+builtins.str(fc)+"." if(dict[o]!=f): return "Closed parenthese "+f+" at line "+builtins.str(fl)+" char "+builtins.str(fc)+" don't match the open parenthese "+o+" at line "+builtins.str(ol)+" char "+builtins.str(oc)+"." if(len(ouv)!=0 and len(fer)==0): o = stack.pop(ouv) ol = stack.pop(ouvLines) oc = stack.pop(ouvChars) return "Parenthese "+o+" at line "+builtins.str(ol)+" char "+builtins.str(oc)+" has no matching closed parenthese." return "Well parenthesed."