def __init__(self, str): self.str = str self.matrix = [[0 for col in range(9)] for row in range(9)] self.possible_cell = { i: [1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(81) } self.init_check = {i: 0 for i in range(81)} #判别该格数值是否能改 self.count = 0 self.stack = ArrayStack()
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 print_reverse_order(): words_stack = ArrayStack() stop = False while not stop: word = input('Please input a word: ').strip() if word == 'stop': stop = True break words_stack.push(word) reverse = '' while not words_stack.is_empty(): reverse += (f' {words_stack.pop()}') print(f'Your words in reverse order: {reverse.lstrip()}')
def test_size(self): # empty stack stack = ArrayStack() self.assertEqual(stack.size(), 0) # one item stack.push('a') self.assertEqual(stack.size(), 1) # +1 item stack.push('b') self.assertEqual(stack.size(), 2)
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 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()
def __assign_army(self, name: str, sold: int, arch: int, cav: int, formation: int) -> str: """ method sets the formation of the army to either stack or queue form, depending on the value of formation (0 = stack and 1 = queue) # @ Complexity: The inner loop runs O(n), n been the size of each army chosen and the outer run is constant, so the best case is O(1) and the worst case is O(n) for both formation 0 and formation 1 """ sol_object = Soldier() # calling Soldier object ach_object = Archer() # calling Archer object cav_object = Cavalry() # calling Cavalry object player_input = [sold, arch, cav] # list containing player input size = len(player_input) # length of the player input -- 3 player_object = [sol_object, ach_object, cav_object] # player soldier, archer, cavalry stack_size = sum([sold, arch, cav]) # size of the players # reverse the stack to enable the soldiers be the FirstInFirstOut and Cavalry LastInLastOut # pushing in a reverse order, solders first and cavalry last. if formation == 0: player_stack = ArrayStack( stack_size) # created stack to hold the armies purchased for i in range(size - 1, -1, -1): # army_object = player_object[i] quantity = player_input[i] for j in range(quantity): player_stack.push(army_object) self.force = player_stack # Circular Queue implementation # appending in a queue style if formation == 1: player_queue = CircularQueue( stack_size) # created Queue to hold the armies purchased for i in range(size): army_object = player_object[i] quantity = player_input[i] for j in range(quantity): player_queue.append(army_object) self.force = player_queue self.name = name
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 test_peek(self): # empty stack stack = ArrayStack() with self.assertRaises(StackException): stack.peek() # add one thing then peek. it should still be there stack.push('a') self.assertEqual(stack.peek(), 'a') self.assertEqual(stack.peek(), 'a')
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 test_is_empty(self): # empty stack stack = ArrayStack() self.assertTrue(stack.is_empty()) # non-empty stack stack.push('a') self.assertFalse(stack.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 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()
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 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()
class CircularBuffer(object): #initialize a new circular buffer that can store at most max_size items def __init__(self, max_size=7): self.list = ArrayStack() self.max = max_size self.size = 0 self.start = 3 self.end = 0 #check if the buffer is empty def is_empty(self): return self.start is None def length(self): return self.size def is_full(self): #check if the buffer is full if self.size == self.max: return ValueError('Buffer is full...') def enqueue(self, item): #insert item at the back of the buffer self.list.end.add(item) self.end += 1 self.size += 1 def front(self): #return the item at the front of the buffer if self.is_empty(): return None return self.list[self.start] def dequeue(self): #remove and return the item at the front of the buffe if self.is_empty(): raise ValueError new_start = self.list.remove(self.start) self.start += 1 self.size -= 1 if self.start == max_size: self.start = self.start - self.max return self.start
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 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 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 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 test_push(self): """ We can push an item on the stack. We should not get an error """ stack = ArrayStack() # nothing sent it with self.assertRaises(TypeError): stack.push() # add a bunch of items and push. no errors mixed_list = [1, 'a', [6, 7, 8], {"cat": "sylvester"}, None] for item in mixed_list: stack.push(item)
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 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 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 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 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 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 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
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 __init__(self, scanner): self._expressionSoFar = "" self._operandStack = ArrayStack() self._scanner = scanner