def __init__(self, num_discs=3, verbose=True): self.tower_1 = Stack() self.tower_2 = Stack() self.tower_3 = Stack() self.num_discs = num_discs self.verbose = verbose # Initialize tower for disc in range(self.num_discs, 0, -1): self.tower_1.push(disc) # Counter for number of recursive calls needed to solve self._num_steps = 0
def traverse_df_po_generator(self, root=None): #deep-first tree traversing if root is None : root = self.root stack = Stack.Stack([root]) ; register = Stack.Stack([len(root.nodes)]) while register.top() : register.decr() ; node = root.nodes[register.top()] ; register.push(len(node.nodes)) while node != root : if register.top() : register.decr() ; stack.push(node) node = node.nodes[register.top()] ; register.push(len(node.nodes)) else : yield node ; node = stack.pop() ; register.dlt() yield root
def test_stacks_to_queues(): print('{}'.format('-' * 20)) print('Start of Task 1 Testing (stacks_to_queues):\n') cases = [[1, 2, 3], [], [10, 20], [100, 200, 300, 400]] sizes = [3, 1, 2, 4] master_stack1 = Stack(len(cases)) for i in range(len(cases) - 1, -1, -1): stack = Stack(sizes[i]) for item in cases[i]: stack.push(item) master_stack1.push(stack) print('master_stack before calling function:') print(master_stack1) print() print('master_queue1 after calling function:') master_queue1 = stacks_to_queues(master_stack1) print(master_queue1) print() print('Verity that master_stack1 is empty after calling function:') print(master_stack1) print() print('Verifying Sizes:') counter = 0 while not master_queue1.is_empty(): print('Queue {} size = {}'.format(counter, master_queue1.remove()._size)) counter += 1 print() master_queue2 = stacks_to_queues(Stack(5)) print('Contents of master_queue if master_stack is empty: {}'.format( master_queue2)) print('Size of master_queue2 = {}'.format(master_queue2._size)) print() master_queue3 = stacks_to_queues(Queue(5)) print('Contents of master_queue if master_stack is invalid: {}'.format( master_queue3)) print('Size of master_queue3 = {}'.format(master_queue2._size)) print() print('End of Task 1 testing') print('{}\n'.format('-' * 20)) return
def get_digits(self): """ This pushes numbers in stack. Then it converts that stack into a dictionary value with an alphabetic key. The reason we do this is that the calculations function cannot handle multiple digits because it is processing each element by character. For example, 2 + 2 can be processed but 10 + 10 cannot because it would be expecting a + - * / operator between the 1 and the 0. It is easier to have proxy variables, such as A + B rather than 10 + 10, and use that to pull dictionary values. The result would look like self.numbers.get('A') + self.numbers.get('B') with the self.numbers dictionary looking like {'A': 10, 'B': 10}. The calculator would read this as 10 + 10 without issue. Thus, the purpose of this function is to build that self.numbers dictionary and build self.final_infix with alphabetical variables substituting multi-digit numbers. self.final_infix is a word that looks like 'A+B'. """ operands = Stack() alphabet_num = 65 for char in self.infix_split: if char in '0123456789.': operands.push(char) elif not operands.isempty(): alphabet = chr(alphabet_num) alphabet_num += 1 number = '' # Converts number into a dictionary item. while not operands.isempty(): number = operands.pop() + number self.numbers[alphabet] = number self.final_infix += alphabet + char else: self.final_infix += char
def dft(self, starting_vertex_id): """ Traverse and print each vertex in depth-first order (DFT) beginning from starting_vertex. """ # Initialize empty stack and set of visited nodes: stack = Stack() visited = set() # Check if provided starting vertex is in our graph: if starting_vertex_id in self.vertices.keys(): # If so, add starting vertex to stack: stack.push(starting_vertex_id) else: return IndexError( f"Provided starting vertex {starting_vertex_id} does not exist in graph!" ) # Process all vertices via BFT: while stack.size() > 0: # Get next vertex to process as first item in stack: current_vertex = stack.pop() # If the current vertex has not already been visited+processed, process it: if current_vertex not in visited: # Process current vertex: print(current_vertex) # Add adjacent vertices to stack for future processing: for adjacent_vertex in self.get_neighbors(current_vertex): stack.push(adjacent_vertex) # Mark current vertex as "visited" by adding to our set of visited vertices: visited.add(current_vertex)
def randomize(maze): stack = Stack() current = maze.board[0][0] visited_count = 0 while True: q = current.get_random_nbr() if not current.visited: visited_count += 1 current.visited = True if q is None: if stack.size > 0: current = stack.pop() else: raise StopIteration() else: next, x = q stack.push(current) current.unlock(x) next.unlock((x + 2) % 4) current = next if visited_count >= maze.length * maze.height: raise StopIteration() yield current
def parenthesis_checker(symbolString): """ Read a string of parenthesis from left to right and decide whether the symbols are balanced """ S = Stack() #Input are valid if symbolString is None: raise TypeError("cannot be none") if not symbolString: raise ValueError("cannot be empty") for char in symbolString: if char == "(": S.push(char) elif char == "[": S.push(char) elif char == "{": S.push(char) else: if S.isEmpty(): return False else: S.pop() return S.isEmpty()
def infixToPostfix(infixexpr): precedence = {} precedence["*"] = 3 precedence["/"] = 3 precedence["+"] = 2 precedence["-"] = 2 precedence["("] = 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 \ (precedence[opStack.peek()] >= precedence[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList)
def evaluate_postfix(expr): if len(expr) == 0: return "Expression is invalid" nums = Stack() for char in expr: if char in "+*-": num1 = nums.pop() num2 = nums.pop() if char == "+": subtotal = num1 + num2 elif char == "*": subtotal = num1 * num2 elif char == "-": subtotal = num2 - num1 nums.push(subtotal) else: nums.push(int(char)) if len(nums._items) > 1: return "Expression is invalid" return nums.pop()
def infixtopostfix(string): comp = string.split(' ') output = [] operator_precedence = {"+": 1, "-": 1, "/": 2, "*": 2, "(": 3, ")": 3} operator_stack = Stack() for value in comp: if value in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or value in '0123456789': output.append(value) elif value == '(': operator_stack.push(value) elif value == ')': operator = operator_stack.pop() while operator != '(': output.append(operator) operator = operator_stack.pop() else: while not operator_stack.isEmpty() and \ operator_precedence[operator_stack.peek()] <= operator_precedence[value]: output.append(operator_stack.pop()) operator_stack.push(value) while not operator_stack.isEmpty(): token = operator_stack.pop() output.append(token) return ' '.join(output)
def buildParseTree(fpexp): exp_list = fpexp.split() # split the expression in a list wth the delimateur being space stack = Stack() current_node = BinaryTree('') tokens = ['+', '-', '/', '*'] #stack.push(current_node) for char in exp: if char == '(': current_node.insertLeft('') S.push(current_node) # push parent into the stack current_node = current_node.leftChild elif char.isdigit(): current_node.key = int(char) current_node = S.pop() elif char in tokens: current_node.insertRight('') current_node.key = char S.push(current_node) current_node = current_node.rightChild elif char == ')': current_node = S.pop() else: raise ValueError
def balanced_parentheses(paren_str): """problem involving applications of stack""" # filter out all values besides brackets matches = re.finditer(r'[(){}[\]]+', paren_str) parsed_iter = itertools.chain.from_iterable( result.group() for result in matches) opening = Stack() for i in parsed_iter: if i in ("(", "{", "["): opening.add(i) else: if not opening.isEmpty(): if i == ")" and opening.peek() == "(": opening.get() elif i == "}" and opening.peek() == "{": opening.get() elif i == "]" and opening.peek() == "[": opening.get() else: return False else: return False return True
def parseTree(expression): tokens = expression.split() tree_holder = Stack() main_tree = BinaryTree('') tree_holder.push(main_tree) currentTree = main_tree for val in tokens: if val == '(': currentTree.add_left('') tree_holder.push(currentTree) currentTree = currentTree.get_left() elif val not in '+-*/': currentTree.set_root_val(val) parent = tree_holder.pop() currentTree = parent elif val in '+-*/': currentTree.set_root_val(val) currentTree.add_right('') tree_holder.push(currentTree) currentTree = currentTree.get_right() elif val == ')': currentTree = tree_holder.pop() else: raise ValueError return main_tree
def calculations(self): """ This is where the calculator does its magic. To see how this function works, please reference the textbook material on Chapter 3 Stacks. This algorithm was built by making an algorithm that takes an infix expression and transforms it into a postfix expression (2+2 --> 22+). Then, by taking that postfix expression and processing the operators and operands it until there is only 1 element in the stack, we get the postfix answer, which is the same answer for the infix expression. (22+ --> 4) It is possible to build a calculator with simply those 2 algorithms linked up to each other. However, this function is a hybrid of the two where it is able to simultaneously work with operators and operands, such that when an infix expression is determined to be in postfix expression, we immediately calculate the answer. """ precedent = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1} operator_stack = Stack() operand_stack = Stack() for item in self.final_infix: if item in string.ascii_letters: operand_stack.push(self.numbers.get(item)) elif item == '(': operator_stack.push(item) elif item == ')': # Here be dragons. top_of_stack = operator_stack.pop() while top_of_stack != '(': operand2 = float(operand_stack.pop()) operand1 = float(operand_stack.pop()) operand_stack.push(self.do_math(top_of_stack, operand1, operand2)) top_of_stack = operator_stack.pop() elif item in precedent: while (not operator_stack.isempty()) and precedent[operator_stack.peek()] >= precedent[item]: operand2 = float(operand_stack.pop()) operand1 = float(operand_stack.pop()) operand_stack.push(self.do_math(operator_stack.pop(), operand1, operand2)) operator_stack.push(item) elif item == '~': # This is a helper variable to signal the end of infix expression and empty all stacks. while not operator_stack.isempty(): operand2 = float(operand_stack.pop()) operand1 = float(operand_stack.pop()) operand_stack.push(self.do_math(operator_stack.pop(), operand1, operand2)) else: raise TypeError('Error: Calculations blew up.') self.answer = operand_stack.pop()
def test_stack(): stack = Stack() stack.push(3) stack.push(2) assert stack.peek() == 2 assert stack.pop() == 2 assert stack.pop() == 3 assert stack.is_empty()
def dfs(self): self.clear() self._display_grid() # frontier is where we've yet to go frontier: Stack[Node[T]] = Stack() frontier.push(Node(self.start, None)) # explored is where we've been explored: Set[T] = {self.start} self.step(frontier, explored, None)
def test_push(): stack, arr = Stack(), [] assert(stack.is_empty()) for expected in range(ITERS): stack.push(expected) arr = [expected] + arr actual = stack.peek() assert(len(stack) == len(arr)) assert(expected == actual) assert(not stack.is_empty())
def test_push(self): """ Test Case to test the push operation """ stack = Stack() stack.push(1) self.assertEqual(stack.top, 1) stack.push(2) stack.push(3) self.assertEqual(stack.top, 3)
def execute_df(self, root=None, exec_pr=Tree._func_pass, exec_in=Tree._func_pass, exec_po=Tree._func_pass, **kwargs): #deep-first tree traversing if root is None : root = self.root exec_pr(root, **kwargs) #pre-order call stack = Stack.Stack([root]) ; register = Stack.Stack([len(root.nodes)]) if not len(root.nodes) : exec_in(root, **kwargs) #in-order call while register.top() : if register.top() == len(root.nodes) - 1 : exec_in(root, **kwargs) #in-order call register.decr() ; node = root.nodes[register.top()] ; register.push(len(node.nodes)) exec_pr(node, **kwargs) #pre-order call while node != root : if not len(node.nodes) or register.top() == len(node.nodes) - 1 : exec_in(node, **kwargs) #in-order call if register.top() : register.decr() ; stack.push(node) ; node = node.nodes[register.top()] ; register.push(len(node.nodes)) else : exec_po(node, **kwargs) #post-order call node = stack.pop() ; register.dlt() exec_po(root, **kwargs) #post-order call
def insert_node(self, node): lessFreq_stack = Stack() while self.stack.num_elements>0 and self.stack.top().get_freq() < node.get_freq(): lessFreq_stack.push(self.stack.pop()) self.stack.push(node) while lessFreq_stack.num_elements>0: self.stack.push(lessFreq_stack.pop())
def test_dfs_assert_equal_return_lists(self): visited_list, path_list = dfs(self.grid, self.start, self.end, _stack=Stack()) self.assertEqual( visited_list, self.dfs_correct_returns["visited_list"], "tested visited_list is not equal to correct visited list") self.assertEqual(path_list, self.dfs_correct_returns["path_list"], "tested path_list is not equal to correct path list")
def dfs(initial, goal_test, successors): """ Depth-first search. Parameters ---------- initial : Generic Starting point of the search. goal_test : Callable Callable returing boolean value indicating search success. successors : Callable Callable returning list of next possible locations in search space. Returns ------- found : Generic Node corresponding to successful goal_test. Returns None if search fails. """ # References to candidate and previously-explored nodes in search space frontier = Stack() explored = Stack() # Initialize candidate search locations with initial condition frontier.push(Node(initial, None)) # Continue search as long as their are candidates in the search space while not frontier.empty: current_node = frontier.pop() current_state = current_node.state # If current node meets goal, then search completes successfully if goal_test(current_state): return current_node # Populate next step in search for child in successors(current_state): # Skip previously-explored states if child in explored: continue explored.push(child) frontier.push(Node(child, current_node)) # Search terminates without finding goal return None
def test_pop(self): """ Test Case to test the pop operation """ stack = Stack() stack.push(1) num = stack.pop() self.assertEqual(num, 1) stack.push(2) stack.push(3) num = stack.pop() self.assertEqual(num, 3)
def HexToBinary(number): bin_holder = Stack() while number > 0: rem = number % 2 bin_holder.push(rem) number = number // 2 bin_string = "" while not bin_holder.isEmpty(): bin_string = bin_string + str(bin_holder.pop()) return bin_string
def test_size(self): """ Test Case to check the size of the stack after push and pop operations """ stack = Stack() self.assertEqual(stack.length, 0, STACK_SIZE_ZERO_MSG) stack.push(1) self.assertEqual(stack.length, 1, INCORRECT_STACK_SIZE_MSG) stack.push(2) stack.push(3) self.assertEqual(stack.length, 3, INCORRECT_STACK_SIZE_MSG) stack.pop() self.assertEqual(stack.length, 2, INCORRECT_STACK_SIZE_MSG)
def test_pop_on_empty_stack(self): """ Test Case to test pop operation on Empty Stack """ stack = Stack() stack.push(1) stack.pop() self.assertEqual(stack.length, 0, STACK_SIZE_ZERO_MSG) # Stack should be empty after one push and one pop operation # Should raise EmptyStackException on pop() with self.assertRaises(exceptions.EmptyStackException): stack.pop()
def postfixEval(postfixExpr): operandStack = Stack() tokenList = postfixExpr.split() for token in tokenList: if token.isdigit(): operandStack.push(int(token)) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) return operandStack.pop()
def revstringstack(str): # with stack implemented stack = Stack() for char in str: stack.add(char) new_str = '' while not stack.isEmpty(): new_str += stack.get() return new_str
def rev_string(my_string): """Uses stack to reverse characters in string""" chars = Stack() for char in my_string: chars.push(char) reversed_string = '' while not chars.is_empty(): reversed_string += chars.pop() return reversed_string
def test_stack(): f = Stack() test_array = [i for i in range(100)] for i in test_array: f.push(i) result = [] while not f.is_empty(): result.append(f.pop()) test_array.reverse() assert test_array == result