def solveMaze(row, column, maze): stack = ArrayStack() stack.push((row, column)) while not stack.isEmpty(): (row, column) = stack.peek() if maze[row][column] == 'T': return stack elif maze[row][column] != '.': maze[row][column] = '.' counter = 0 ###adjacent cells based on changing x,y values so need 4 options if row != 0 and not maze[row - 1][column] in ('*', '.'): stack.push((row-1, column)) counter += 1 if row + 1 != maze.getHeight() and not maze[row + 1][column] in ('*', '.'): stack.push((row + 1, column)) counter += 1 if column + 1 != maze.getWidth() and not maze[row][column + 1] in ('*', '.'): stack.push((row, column + 1)) counter += 1 if column != 0 and not maze[row][column -1] in ('*', '.'): stack.push((row, column - 1)) counter += 1 if counter == 0: stack.pop() return None
def bodmas(exp): expr = exp.split() oper = ArrayStack() nums = ArrayStack() for a in expr: if a.isdigit() == True: nums.push(a) elif a in ['+', '-', '*', '/']: oper.push(a) else: continue while oper.isempty() == False: a = int(nums.pop()) b = int(nums.pop()) op = oper.pop() if op == '+': result = b + a if op == '-': result = b - a if op == '*': result = b * a if op == '/': result = b / a nums.push(result) return (result)
class TestArrayStack(unittest.TestCase): def setUp(self): self.st = ArrayStack() def tearDown(self): del self.st # default feature test - push, pop, peek def test_01(self): self.st.push(1) self.st.push(2) self.st.push(3) self.assertEqual(self.st.peek(), 3) self.assertEqual(self.st.pop(), 3) self.assertEqual(self.st.peek(), 2) self.assertEqual(self.st.pop(), 2) self.assertEqual(self.st.peek(), 1) self.assertEqual(self.st.pop(), 1) # raise error when pop with empty stack def test_02(self): with self.assertRaises(IndexError) as cm: self.st.pop() self.assertEqual("stack is empty", str(cm.exception)) # test check empty def test_03(self): self.assertTrue(self.st.is_empty()) # test expand def test_04(self): self.assertEqual(len(self.st._array), 10) for i in range(11): self.st.push(i) self.assertEqual(len(self.st._array), 20)
def infix_to_potfix(token_list): """ 들어온 중위 표현식을 후위 표현식으로 변경 :param token_list: :return: 후위 표현식 """ prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1} opStack = ArrayStack() result = [] for token in token_list: if isinstance(token, int): result.append(token) elif token == '(': opStack.push(token) elif token == ')': while opStack.peek() != '(': result.append(opStack.pop()) opStack.pop() else: if not opStack.isEmpty(): if prec[opStack.peek()] >= prec[token]: result.append(opStack.pop()) opStack.push(token) else: opStack.push(token) else: opStack.push(token) while not opStack.isEmpty(): result.append(opStack.pop()) print(result) return result
class StackQueue: def __init__(self): self.stack1 = ArrayStack() self.stack2 = ArrayStack() self.count = 0 def enqueue(self, item): self.stack1.push(item) self.count += 1 def dequeue(self): if self.is_empty(): raise ValueError("Empty Queue Error") self.moveStack1ToStack2() return self.stack2.pop() def peek(self): if self.is_empty(): raise ValueError("Empty Queue Error") self.moveStack1ToStack2() return self.stack2.peek() def moveStack1ToStack2(self): if self.stack2.is_empty(): while not self.stack1.is_empty(): self.stack2.push(self.stack1.pop()) def is_empty(self): return self.stack1.is_empty() and self.stack2.is_empty()
def post_fix_eval(expr): """ 후위 표현식으로 된 식을 계산 :param expr: :return: """ val_stack = ArrayStack() for token in expr: if isinstance(token, int): val_stack.push(token) elif token == '+': num1 = val_stack.pop() num2 = val_stack.pop() val_stack.push(num2 + num1) elif token == '-': num1 = val_stack.pop() num2 = val_stack.pop() val_stack.push(num2 - num1) elif token == '/': num1 = val_stack.pop() num2 = val_stack.pop() val_stack.push(num2 / num1) elif token == '*': num1 = val_stack.pop() num2 = val_stack.pop() val_stack.push(num2 * num1) return val_stack.pop()
class PFEvaluator(object): def __init__(self, scanner): self._expressionSoFar = "" self._operandStack = ArrayStack() self._scanner = scanner def evaluate(self): while self._scanner.hasNext(): currentToken = self._scanner.next() self._expressionSoFar += str(currentToken) + " " if currentToken.getType() == Token.INT: self._operandStack.push(currentToken) elif currentToken.isOperator(): if len(self._operandStack) < 2: raise Exception, \ "Too few operands on the stack" t2 = self._operandStack.pop() t1 = self._operandStack.pop() result = Token(self._computeValue(currentToken, t1.getValue(), t2.getValue())) self._operandStack.push(result) else: raise Exception, "Unknown token type" if len(self._operandStack) > 1: raise Exception, "Too many operands on the stack" result = self._operandStack.pop() return result.getValue(); def __str__(self): result = "\n" if self._expressionSoFar == "": result += "Portion of expression processed: none\n" else: result += "Portion of expression processed: " + \ self._expressionSoFar + "\n" if self._operandStack.isEmpty(): result += "The stack is empty" else: result += "Operands on the stack : " + \ str(self._operandStack) return result def _computeValue(self, op, value1, value2): result = 0; theType = op.getType() if theType == Token.PLUS: result = value1 + value2; elif theType == Token.MINUS: result = value1 - value2; elif theType == Token.MUL: result = value1 * value2; elif theType == Token.DIV: result = value1 / value2; else: raise Exception, "Unknown operator" return result
class PFEvaluator(object): def __init__(self, scanner): self._expressionSoFar = "" self._operandStack = ArrayStack() self._scanner = scanner def evaluate(self): while self._scanner.hasNext(): currentToken = self._scanner.next() self._expressionSoFar += str(currentToken) + " " if currentToken.getType() == Token.INT: self._operandStack.push(currentToken) elif currentToken.isOperator(): if len(self._operandStack) < 2: raise Exception, \ "Too few operands on the stack" t2 = self._operandStack.pop() t1 = self._operandStack.pop() result = Token( self._computeValue(currentToken, t1.getValue(), t2.getValue())) self._operandStack.push(result) else: raise Exception, "Unknown token type" if len(self._operandStack) > 1: raise Exception, "Too many operands on the stack" result = self._operandStack.pop() return result.getValue() def __str__(self): result = "\n" if self._expressionSoFar == "": result += "Portion of expression processed: none\n" else: result += "Portion of expression processed: " + \ self._expressionSoFar + "\n" if self._operandStack.isEmpty(): result += "The stack is empty" else: result += "Operands on the stack : " + \ str(self._operandStack) return result def _computeValue(self, op, value1, value2): result = 0 theType = op.getType() if theType == Token.PLUS: result = value1 + value2 elif theType == Token.MINUS: result = value1 - value2 elif theType == Token.MUL: result = value1 * value2 elif theType == Token.DIV: result = value1 / value2 else: raise Exception, "Unknown operator" return result
def is_matched_html(raw): """ Returns True if all HTML tags are properly matched, False otherwise """ S = ArrayStack() j = raw.find('<') # find first < character if any while j != -1: k = raw.find(">",j+1) # find next > character if any if k==-1: return False # invalid tag tag = raw[j+1:k] # dtrip away <> if not tag.startswith('/'): S.push(tag) else: if S.is_empty(): return False if tag[1:] != S.pop(): return False j = raw.find("<",k+1) return S.is_empty()
class TwoStackQueue(): def __init__(self, length): self.stack_first = ArrayStack(length) self.stack_second = ArrayStack(length) def enqueue(self, value): self.stack_first.push(value) def dequeue(self): while self.stack_first.top != 0: self.stack_second.push(self.stack_first.pop()) value = self.stack_second.pop() while self.stack_second.top != 0: self.stack_first.push(self.stack_second.pop()) return value
def reverse_file(filename): S = ArrayStack() original = open(filename) for line in original: S.push(line.rstrip("\n")) original.close() output = open(filename, 'w') while not S.is_empty(): output.write(S.pop() + "\n") output.close()
def reverse(): S = ArrayStack() original = open(sys.argv[1]) for line in original: S.push(line) original.close() output = open(sys.argv[1], 'w') while not S.is_empty(): output.write(S.pop()) output.close()
def reverse_file(filename): S = ArrayStack() original = open(filename) for line in original: S.push(line.rstrip("\n")) original.close() output = open(filename, "w") while not S.is_empty(): output.write(S.pop() + "\n") output.close()
def multiBaseOutput(num, b): stk = ArrayStack() s1 = '' while num != 0: stk.push(str(num % b)) num = num // b while not stk.isEmpty(): s1 += stk.pop() return s1
def reverse_file(filename): """ Overwrite given file with its contents line-by-line reversed. """ S = ArrayStack() original = open(filename) for line in original: S.push(line.rstrip('\n')) # we will re-insert newlines when writing original.close() # now we overwrite with contents in LIFO order output = open(filename, 'w') while not S.is_empty(): output.write(S.pop() + '\n') output.close()
def is_matched(expr): lefty = '({[' righty = ')}]' S = ArrayStack() for c in expr: if c in lefty: S.push(c) elif c in righty: if S.is_empty(): return False if righty.index(c) != lefty.index(S.pop()): return False return S.is_empty()
class QueueTests(unittest.TestCase): def setUp(self): self.stack = ArrayStack() def test_len_returns_0_for_empty_stack(self): self.assertEqual(len(self.stack), 0) def test_len_returns_correct_length_after_push(self): self.assertEqual(len(self.stack), 0) self.stack.push(2) self.assertEqual(len(self.stack), 1) self.stack.push(4) self.assertEqual(len(self.stack), 2) self.stack.push(6) self.stack.push(8) self.stack.push(10) self.stack.push(12) self.stack.push(14) self.stack.push(16) self.stack.push(18) self.assertEqual(len(self.stack), 9) def test_empty_pop(self): self.assertIsNone(self.stack.pop()) self.assertEqual(len(self.stack), 0) def test_pop_respects_order(self): self.stack.push(100) self.stack.push(101) self.stack.push(105) self.assertEqual(self.stack.pop(), 105) self.assertEqual(len(self.stack), 2) self.assertEqual(self.stack.pop(), 101) self.assertEqual(len(self.stack), 1) self.assertEqual(self.stack.pop(), 100) self.assertEqual(len(self.stack), 0) self.assertIsNone(self.stack.pop()) self.assertEqual(len(self.stack), 0)
def reverse_file(filename): """ overwrite given file with its contents line by line reversed """ S = ArrayStack() original = open(filename) for line in original: S.push(line.rstrip('\n')) original.close() output = open(filename, "w") while not S.is_empty(): output.write(S.pop() + "\n") output.close()
def is_matched(expr): """ Return True if all delimiters are properly match;False otherwise. """ lefty = '({[' righty = ')}]' S = ArrayStack() for c in expr: if c in lefty: S.push(c) elif c in righty: if S.is_empty(): return False if righty.index(c) != lefty.index(S.pop()): return False return S.is_empty()
def balanced(expr): ''' checks if all the delimiters in an expression, expr, are balanced ''' lefts = '({[' # opening delimiters rights = ')}]' # respective closing delimiters stack = Stack() for d in expr: if d in lefts: stack.push(d) # first left delimiter, save for later check elif d in rights: if stack.is_empty(): # closing delimiter with no matching opening delimiter return False if rights.index(d) != lefts.index(stack.pop()): #compare match return False return stack.is_empty() # check if all symbols were matched
def solve(self, showSolution=False): """ Uses backtracking algorithm to solve maze. Returns "SUCCESS" or "FAILURE" if the maze can or cannot be solved. Optionally, prints the solved maze. """ # Instantiate empty stack to record coordinates to evaluate. coords = ArrayStack() # Search for starting point. # Push onto coords when found. searching = True while searching: for row in range(self.getHeight()): for col in range(self.getWidth()): if self._data[row][col] == self._start: coords.push((row, col)) searching = False print "Starting point found at (%d, %d)." % (row, col) if searching: raise Exception("No valid starting point found.") # Search for end point value until found, or until # no possible moves exist. searching = True while searching: active = coords.pop() if active: activeValue = self._data[active[0]][active[1]] if activeValue == self._path: self.setCoord(active[0], active[1], ".") adjacent = findAdjacent(active[0], active[1], self.getHeight(), self.getWidth()) for coord in adjacent: if self._data[coord[0]][coord[1]] == self._end: print("SUCCESS: Endpoint found at (%d, %d)." % (coord[0], coord[1])) if showSolution: print "Solution: \n", str(self) searching = False elif self._data[coord[0]][coord[1]] == self._path: coords.push(coord) else: print "FAILURE: No solution found." if showSolution: print "Attempted solution: \n", str(self) searching = False
def is_matched(expr): """ Return True if all the delimeter are properly matched """ lefty = "({[" righty = ")}]" S = ArrayStack() for c in expr: if c in lefty: S.push(c) elif c in righty: if S.is_empty(): return False if righty.index(c) != lefty.index(S.pop()): return False return S.is_empty()
def DFS(G, a): status={} for node in G.nodes(): status[node]='U' nodes=ArrayStack() nodes.push(a) status[a]='V' while nodes.isempty()==False: pnode=nodes.pop() status[pnode]='P' print(pnode) for node in G.neighbors(pnode): if status[node]=='U': nodes.push(node) status[node]='V' return
def reverse(): ''' replace the text in a file by a reverse of itself ''' stack = Stack() # read original data into stack with open('text.txt', 'r') as original: for line in original: stack.push(line.rstrip('\n')) original.close() # write data from stack to file with open('text.txt', 'w') as output: while not stack.is_empty(): output.write(stack.pop() + '\n') output.close()
def maze_solver(maze, starting_pt, target_pt): """Implement backtracking algorithms using a stack to solve a maze""" if_solvable = False maze_stack = ArrayStack() path = {} maze_stack.push(starting_pt) while not maze_stack.isEmpty(): location = maze_stack.pop() if maze[location[0]][location[1]] == 'T': if_solvable = True elif maze[location[0]][location[1]] != '.': maze[location[0]][location[1]] = '.' nrs = check_neighbours(maze, location[0], location[1]) for nr in nrs: maze_stack.push(nr) path[nr] = location return if_solvable, path
class PreorderIteratorStack(Generic[T]): def __init__(self, root: BinaryTreeNode[K, I]) -> None: self.stack = ArrayStack() self.stack.push(root) def __iter__(self): return self def __next__(self) -> T: if self.stack.is_empty(): raise StopIteration current = self.stack.pop() if current.right is not None: self.stack.push(current.right) if current.left is not None: self.stack.push(current.left) return current.item
def test_pop(self): """ We can pop an item from the stack """ # empty stack stack = ArrayStack() with self.assertRaises(StackException): stack.pop() # add one thing then pop stack.push('a') self.assertEqual(stack.pop(), 'a') with self.assertRaises(StackException): stack.pop() # add 3 things then pop stack.push('a') stack.push('b') stack.push('c') self.assertEqual(stack.pop(), 'c') self.assertEqual(stack.pop(), 'b') self.assertEqual(stack.pop(), 'a') with self.assertRaises(StackException): stack.pop()
def bracketsBalance(exp, Open, Close): """exp represents the expression""" stk = ArrayStack() # Create a new stack for ch in exp: # Scan across the expression if ch in Open: # Push an opening bracket stk.push(ch) elif ch in Close: # Process a closing bracket if stk.isEmpty(): # Not balanced return False chFromStack = stk.pop() # Brackets must be of same type and match up OpenIndex = Open.index(chFromStack) CloseIndex = Close.index(ch) if OpenIndex != CloseIndex: return False return stk.isEmpty() # They all matched up
def is_matched_html(raw): """ Return True if all HTML tags are properly match; False otherwise. """ S = ArrayStack() # find():返回子字符串 sub 在 s[start:end] 切片内被找到的最小索引。 可选参数 start 与 end 会被解读为切片表示法。 如果 sub 未被找到则返回 -1。 j = raw.find('<') # find first'<' character while j != -1: k = raw.find('>', j + 1) # find next '>' if k == -1: return False tag = raw[j + 1:k] if not tag.startswith('/'): S.push(tag) else: if S.is_empty(): return False if tag[1:] != S.pop(): return False j = raw.find('<', k + 1) return S.is_empty()
def isMatchedHTML(raw): # find "<" then find next ">", after that, get the tag if starting with / then it is the ending tag, pop.otherwise, it is starting tag,push into stack S = ArrayStack() i = raw.find("<") # this will find the first "<" while i != -1: j = raw.find(">", i + 1) if j == -1: return False tag = raw[i + 1 : j] if not tag.startswith("/"): S.push(tag) else: if S.is_empty(): return False else: if S.pop() != tag[1:]: return False i = raw.find("<", j + 1) return S.is_empty()
def isMatchedHTML(raw): # find "<" then find next ">", after that, get the tag if starting with / then it is the ending tag, pop.otherwise, it is starting tag,push into stack S = ArrayStack() i = raw.find("<") # this will find the first "<" while i != -1: j = raw.find(">", i + 1) if j == -1: return False tag = raw[i + 1:j] if not tag.startswith("/"): S.push(tag) else: if S.is_empty(): return False else: if S.pop() != tag[1:]: return False i = raw.find("<", j + 1) return S.is_empty()
def is_brackets(expr): match = { ')':'(', ']':'[', '}':'{' } S = ArrayStack() for c in expr: if c in '({[': S.push(c) else: if S.isEmpty(): return False else: bracket = S.pop() if bracket != match[c]: return False return S.isEmpty() # 스택이 비어있지 않으면 괄호가 안맞음.
def closetags(html): ''' checks if all tags in a html block are closed ''' stack = Stack() # is there an opening angle? find it i = html.find('<') while i != -1: j = html.find('>', i + 1) # finding the next > character if j == -1: return False # invalid tag tag = html[i + 1:j] # slice of the tag from html if not tag.startswith('/'): stack.push(tag) # its an opening tag, store in stack else: if stack.is_empty(): return False # closing tag found without an opening tag if tag[1:] != stack.pop(): return False # mismatched tag i = html.find('<', j + 1) return stack.is_empty()
def is_matched(string): #创建一个栈 s = ArrayStack() left = '{[(' right = '}])' #遍历这个字符串 for c in string: #如果c在left中则放入s中 if c in left: s.push(c) elif c in right: if s.is_empty(): #如果c在栈中,但是栈却为空说明缺少左边的匹配 列如 ))、{)}、{[)]} return False #c在right中,拿c在right中的索引 和 栈顶元素在left中的索引做比较,并且移除栈顶元素。列如 (}、([})、[}] if right.index(c) != left.index(s.pop()): return False #如果string为(( ,缺少右侧括号匹配,则栈不为空,返回false return s.is_empty()
def isMatch(s): left = "{[(" right = ")]}" S = ArrayStack() for c in s: if c in left: S.push(c) elif c in right: # what id didnt have before # should check empty first if S.is_empty(): return False # if right.index(c) != left.index(S.pop()) # return False cc = S.pop() if not cc+c in ["{}","()","[]"]: return False else: raise Exception("Invalid string") if S.is_empty(): return True else: return False