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)
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
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 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()
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 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')
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(): 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 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 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()
def __assign_army(self, name: str, soldier_size: int, archer_size: int, cavalry_size: int, formation: int) -> None: '''Creates size of army based on user's choices. Formations can only be in Stack (0) or Queue (1) formations. Soldiers will go first, then Archers, and lastly Cavalry. :complexity: Best and Worst O(sold*arch*cav) as the for loops run based on the inputs made by the users, and there was no early exit condition :preconditions: formation argument can only accept 0 or 1 as integers ''' if not formation == 0 and not formation == 1: # precondition check raise Exception("Formation must either by STACK(0) or QUEUE(1)") total_size = soldier_size + archer_size + cavalry_size # to create size of army if formation == 0: # Formation will be in Stack ADT, follows First In Last Out army = ArrayStack(total_size) # pushes cavalry into formation for _ in range(cavalry_size): army.push(Cavalry()) # pushes archers into formation for _ in range(archer_size): army.push(Archer()) # pushes soldiers into formation for _ in range(soldier_size): army.push(Soldier()) elif formation == 1: # Formation will be in Queue ADT, follows First In First Out army = CircularQueue(total_size) # pushes soldiers into formation for _ in range(soldier_size): army.append(Soldier()) # pushes archers into formation for _ in range(archer_size): army.append(Archer()) # pushes cavalry into formation for _ in range(cavalry_size): army.append(Cavalry()) # returns the attributes of the player and their army self.name = name self.force = army
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 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 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 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 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 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
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
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 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 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