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 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 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_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_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 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 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 reverseString(stack, string): for character in string: stack.push(character) reversedString = "" while not stack.isEmpty(): reversedString += stack.pop() return reversedString
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 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 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 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 test_length(self): """ -- Verifica el numero de elementos de la lsita cuando son mayores a 1 """ L = LinkedList() push(L, "hola") push(L, "jorge") push(L, "como") push(L, "va?") res = length(L) self.assertEqual(res, 4)
def __init__(self, arr): self.length = len(arr) self.arr = tf.Variable(arr, dtype=tf.int32) left = tf.constant(0, dtype=tf.int32) right = tf.constant(0, dtype=tf.int32) last = tf.constant(0, dtype=tf.int32) index = tf.constant(0, dtype=tf.int32) s0 = tf.constant([-1] * self.length, dtype=tf.int32) p0 = tf.constant(0, dtype=tf.int32) s1, p1 = push(s0, p0, self.length - 1, length=self.length) s2, p2 = push(s1, p1, 0, length=self.length) self.graph = tf.while_loop( self.cond_outer, self.body_outer, [self.arr, index, s2, p2, left, right, last])
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 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 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 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 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 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 iterativePostorderBtree(r): s1 = Stack() s2 = Stack() push(s1, r) while not IsEmptyStack(s1): t = spop(s1) push(s2, t) if t.left is not None: push(s1, t.left) if t.right is not None: push(s2, t.right) while not IsEmptyStack(s2): print(spop(s2).data)
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 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 main(): """ Creates 3 cans, one for each color, and stores them in a list. Then asks the user to input a string of characters containing the letters "R", "G", and "B" corresponding to the different ball colors. Calls the animate_init function to setup the balls in the animation then places each ball in a stack formed by a dataclass structure. After this it uses my solve_puzzle function to solve the puzzle and displays the amount of moves it takes to sort the balls. Asks the user to close the window and calls the animate_finish function to stop the animation. :return: None """ red_can = stack.make_empty_stack() blue_can = stack.make_empty_stack() green_can = stack.make_empty_stack() cans = [red_can, green_can, blue_can] balls = input("Please input your desired balls: ") animate.animate_init(balls) for ch in balls: stack.push(red_can, ch) print("Moves required: ", solve_puzzle(red_can, green_can, blue_can)) print("Close the window to quit.") animate.animate_finish()
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 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 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 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()
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')) elif RPN_list[i] == '/': stack.push(RPN_stack, format(num1 / num2, '.2f')) elif RPN_list[i] == '-': stack.push(RPN_stack, format(num1 - num2, '.2f')) else: stack.push(RPN_stack, RPN_list[i]) i = i + 1 if len(RPN_stack) >= 1: state == "Error"
import stack #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()
for c in inp_list: #is an operator if is_Operator(c): if c == '=': evaluation = stack.pop(s) if evaluation == None: #stack is empty print('Evaluation error') sys.exit(1) #exit program elif c == '*': o2 = stack.pop(s) o1 = stack.pop(s) if o1 == None or o2 == None: #stack underflow print('Evaluation error') sys.exit(1) #exit program result = o1 * o2 stack.push(s, result) elif c == '/': o2 = stack.pop(s) o1 = stack.pop(s) if o1 == None or o2 == None: #stack underflow print('Evaluation error') sys.exit(1) if o2 == 0: print('Evaluation error') #divide by 0 sys.exit(1) result = o1 / o2 stack.push(s, result) elif c == '+': o2 = stack.pop(s) o1 = stack.pop(s) if o1 == None or o2 == None: #stack underflow
import stack if not stack.empty(): x = stack.pop() # qualify by module name stack.push(1.23)
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 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))
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.')