class SingletonTestCase(unittest.TestCase): """Check whether adding a single item makes it appear at the front. """ def setUp(self): """Set up a queue with a single element. """ self.stack = Stack() self.stack.add('a') def tearDown(self): """Clean up. """ self.stack = None def testIsEmpty(self): """Test is_empty() on non-empty Stack. """ self.assertFalse(self.stack.is_empty(), 'is_empty returned True on non-empty Stack!') def testRemove(self): """Test remove() on a non-empty Stack. """ front = self.stack.remove() self.assertEqual( front, 'a', 'The item at the front should have been "a" but was ' + front + '.') self.assertTrue(self.stack.is_empty(), 'Queue with one element not empty after remove().')
class EmptyTestCase(unittest.TestCase): """Test behaviour of an empty Stack. """ def setUp(self): """Set up an empty Stack. """ self.stack = Stack() def tearDown(self): """Clean up. """ self.stack = None def testIsEmpty(self): """Test is_empty() on empty Stack. """ self.assertTrue(self.stack.is_empty(), 'is_empty returned False on an empty Stack!') def testadd(self): """Test add to empty Stack.""" self.stack.add("foo") self.assertEqual(self.stack.remove(), "foo")
def search(robot): maze = Maze() to_be_explored = Stack() backtrace_directions = Stack() current_square = create_current_square(robot) current_square.neighbors.bottom = False add_moves(robot, to_be_explored, maze) maze.add_square(current_square, robot.x, robot.y) while to_be_explored.size() > 0: current_move = to_be_explored.pop() if (current_move.x, current_move.y) in maze.squares: continue while not move_valid_from_square(current_move, current_square): back_move = backtrace_directions.pop() robot.rotate_to_direction(get_relative_move(Direction.down, back_move.direction)) robot.move_forward() current_square = create_current_square(robot) robot.rotate_to_direction(current_move.direction) robot.move_forward() backtrace_directions.add(current_move) current_square = create_current_square(robot) add_moves(robot, to_be_explored, maze) maze.add_square(current_square, robot.x, robot.y) maze.link_squares() return maze
class StackAllTestCase(unittest.TestCase): """Comprehensive tests of (non-empty) Stack.""" def setUp(self): """Set up an empty stack.""" self.stack = Stack() def tearDown(self): """Clean up.""" self.stack = None def testAll(self): """Test adding and removeping multiple elements.""" for item in range(20): self.stack.add(item) assert not self.stack.is_empty(), \ 'is_empty() returned True on a non-empty Stack!' expect = 19 while not self.stack.is_empty(): assert self.stack.remove() == expect, \ ('Something wrong on top of the Stack! Expected ' + str(expect) + '.') expect -= 1
class TestEmptyStack(unittest.TestCase): """ Test behaviour of an empty stack """ def setUp(self): """ Set uo an empty stack """ self.stack = Stack() def tearDown(self): """ Clean up """ self.stack = None def testIsEmpty(self): """ Test is_empty() on an empty stack""" #self.assertEqual(self.stack.is_empty(), True) assert self.stack.is_empty(), \ 'is_empty returned False on an empty stack' def testAdd(self): """ Test addding to an empty stack """ self.stack.add('cats') assert self.stack.remove() == 'cats', 'wrong item on the top of the stack'
def helper_mi_add(s: Stack, lst: list) -> None: """ A helper function for minimax_iterative_strategy. Help to add items from lst to stack s. """ for item in lst: s.add(item)
def validate_parentheses(aString): s = Stack() balanced = False index = 0 while index < len(aString) and not balanced: symbol = aString[index] if symbol in '({[': s.add(symbol) else: top = s[-1] if match(top, symbol): s.remove() else: balanced = True index += 1 if s.isEmpty() and not balanced: return True else: return False
class TypicalTestCase(unittest.TestCase): """A comprehensive tester of typical behaviour of Stack. """ def setUp(self): """Set up an empty stack. """ self.stack = Stack() def tearDown(self): """Clean up. """ self.stack = None def testAll(self): """Check adding and removing several items. """ for item in range(20): self.stack.add(item) self.assertFalse( self.stack.is_empty(), 'Stack should not be empty after adding item ' + str(item)) item = 19 while not self.stack.is_empty(): front = self.stack.remove() self.assertEqual( front, item, 'Wrong item at the front of the Stack. Found ' + str(front) + ' but expected ' + str(item)) item -= 1
def isValid(self, s): valid = Stack() for p in s: if p == "(" or p == "[" or p == "{": valid.add(p) # elif p == ")" or p == "]" or p == "}": print(valid.get_stack()) return True
def test_push_items(self): stack = Stack() tests = [1, '0', Stack, lambda x: x, {}, [], None] for test in tests: stack.add(test) assert len(tests) == len(stack)
def list_stack(lst: List[object], u_stack: Stack) -> None: """ Adds each element of the list to the stack """ for item in lst: u_stack.add(item) while not u_stack.is_empty(): item = u_stack.remove() if type(item) == list: for thing in item: u_stack.add(thing) else: print(item)
def list_stack(l: list, s: Stack) -> None: """do the following things mentioed in the lab""" for element in l: s.add(element) while not s.is_empty(): b = s.remove() if not isinstance(b, list): print(b) else: for element in b: s.add(element)
class SingletonTestCase(unittest.TestCase): '''check whether adding a single item makes it appear in the top''' def setUp(self): self.s = Stack() self.s.add('a') def tearDown(self): self.s = None def testIsEmpty(self): self.assertFalse(self.s.is_empty(), 'is_empty returned true on non-empty stack') def testRemove(self): top = self.s.remove() self.assertEqual(top, 'a', 'The item at the top should have been "a" but was ' + top + '.') self.assertTrue(self.s.is_empty, ' stack with one element not empty after remove()')
class TypicalTestCase(unittest.TestCase): def setUp(self): self.s = Stack() def tearDown(self): self.s = None def testAll(self): for item in range(20): self.s.add(item) self.assertFalse(self.s.is_empty(), 'stack should not be empty after adding item ' + str(item)) item = 19 while not self.s.is_empty(): top = self.s.remove() self.assertEqual(top, item, 'wrong item at the top of the stack. Found' + str(top) + ' but expecting ' + str(item)) item -=1
def solve(m,pausing): """Run the maze, m, pausing at each step (or not).""" done = False square = None # current location goal = m.finish # where we're headed #todo = Queue() todo = Stack() todo.add(m.start) # LINEAR operation while (not todo.empty) and (not done): # go to current location square = todo.remove() # LINEAR operation if m.isVisited(square): continue if square == goal: # finished? clear() print('Solved!') print(m) break # not finished. # add neighbors to the pool of places to explore m.visit(square) r,c = square north = r-1,c # row above south = r+1,c # row below east = r,c+1 # etc. west = r,c-1 # update list of to-do items: if m.isClear(north): todo.add(north) if m.isClear(west): todo.add(west) if m.isClear(south): todo.add(south) if m.isClear(east): todo.add(east) # pause, for demonstration if pausing: clear() print(m) response = input('?') done = response == 'q' pausing = response != 'g'
def evaluator(expression): exp = expression pos = 0 operators = {"/": 1, "*": 2, "+": 3, "-": 4} container = Stack() while pos < len(exp): if operators.setdefault(exp[pos], 0) == 1: val = int(container[-2]) / int(container[-1]) container.remove() container.remove() container.add(val) elif operators.setdefault(exp[pos], 0) == 2: val = int(container[-2]) * int(container[-1]) container.remove() container.remove() container.add(val) elif operators.setdefault(exp[pos], 0) == 3: val = int(container[-2]) + int(container[-1]) container.remove() container.remove() container.add(val) elif operators.setdefault(exp[pos], 0) == 4: val = int(container[-2]) - int(container[-1]) container.remove() container.remove() container.add(val) else: container.add(exp[pos]) pos += 1 return container[-1]
def evaluate_score_iterative(state: GameState) -> int: """ Evaluate the state and return its score """ # I have used a file from lab 3 that contains class # Stack and its funcitons def find_add_children(element, container) -> None: """ Find children for a tree state and add it back into the stack """ for move in element.cur_state.get_possible_moves(): child_tree = Tree(element.cur_state.make_move(move)) element.children.append(child_tree) container.add(child_tree) stk = Stack() tree_state = Tree(state) stk.add(tree_state) while not stk.is_empty(): top_element = stk.remove() if game.is_over(top_element.cur_state): old_state = game.current_state game.current_state = top_element.cur_state if not (game.is_winner("p1") or game.is_winner("p2")): top_element.state_score = 0 elif game.is_winner\ (top_element.cur_state.get_current_player_name()): top_element.state_score = 1 else: top_element.state_score = -1 game.current_state = old_state else: if top_element.children == []: stk.add(top_element) find_add_children(top_element, stk) else: top_element.state_score = max([ -1 * child.state_score for child in top_element.children ]) return tree_state.state_score
def minimax_iterative_strategy(game: Any) -> Any: """ Return a move that minimizes the possible loss for a player, iteratively. """ current_state = IterativeMinimax(game.current_state) s = Stack() s.add(current_state) old_items = [] while not s.is_empty(): current_item = s.remove() if current_item.state.get_possible_moves() != []: if not current_item.is_visited(): movement = current_item.state.get_possible_moves() new_states = [ IterativeMinimax(current_item.state.make_move(move)) for move in movement ] current_item.children = [child for child in new_states] s.add(current_item) helper_mi_add(s, new_states) elif current_item.is_visited(): helper_mi_score(current_item, old_items) old_items.append(current_item) if current_item.state.get_possible_moves() == []: old_state = game.current_state game.current_state = current_item.state if game.is_winner(game.current_state.get_current_player_name()): current_item.score = 1 if game.is_winner('p1') or game.is_winner('p2'): current_item.score = -1 else: current_item.score = 0 old_items.append(current_item) game.current_state = old_state choices = [child.score * -1 for child in current_state.children] best_move = choices.index(max(choices)) return game.current_state.get_possible_moves()[best_move]
def double_items(stack: Stack) -> None: """Double all items in the given stack Precondition: stack contains only numbers >>> stack = Stack() >>> stack.add(1) >>> stack.add(2) >>> double_items(stack) >>> stack.remove() 4 >>> stack.remove() 2 """ temp = Stack() while not stack.is_empty(): temp.add(stack.remove() + 1) while not temp.is_empty(): stack.add(temp.remove())
def BaseConvertor(dec_value,base): values = "0123456789ABCDEF" s = Stack() result = '' while dec_value != 0: value = values[dec_value%base] s.add(value) dec_value = dec_value//base while not s.isEmpty(): get_last_item = s[-1] #print(get_last_item) s.remove() result += str(get_last_item) #print(result,) return result
def get_largest(stack: Stack) -> int: """Return the largest from the stack. Precondition: stack contains only int >>> stack = Stack() >>> stack.add(1) >>> stack.add(2) >>> get_largest(stack) 2 """ temp = Stack() largest = stack.remove() temp.add(largest) while not stack.is_empty(): item = stack.remove() if item > largest: largest = item temp.add(item) while not temp.is_empty(): stack.add(temp.remove()) return largest
def copy_stack(stack: Stack) -> Stack: """Remove a new Stack that is identical to the given stack >>> stack = Stack() >>> stack.add(1) >>> stack.add(2) >>> stack2 = copy_stack(stack) >>> stack.remove() == stack2.remove() True >>> stack.remove() == stack2.remove() True >>> stack.is_empty() and stack2.is_empty() True """ temp = Stack() result = Stack() while not stack.is_empty(): temp.add(stack.remove()) while not temp.is_empty(): item = temp.remove() stack.add(item) result.add(item) return result
def reverse(stack: Stack) -> None: """Reverse the order of <stack>. @param Stack stack: @rtype: None >>> stack = Stack() >>> stack.add(1) >>> stack.add(2) >>> reverse(stack) >>> stack.remove() 1 >>> stack.remove() 2 """ temp1 = Stack() temp2 = Stack() while not stack.is_empty(): temp1.add(stack.remove()) while not temp1.is_empty(): temp2.add(temp1.remove()) while not temp2.is_empty(): stack.add(temp2.remove())
def iterative_minimax(game: 'Game') -> Any: """ Return a minimax move for the game using iteration. """ if game.is_over(game.current_state) is True: return None a = Stack() b = Tree(game.current_state) a.add(b) while a.is_empty() is False: c = a.remove() if game.is_over(c.value) is True: game1 = copy.copy(game) game1.current_state = c.value c.score = score(game1) elif c.children == []: m = c.value.get_possible_moves() states = [c.value.make_move(move) for move in m] trees = [Tree(state) for state in states] c.children = trees a.add(c) for tree in c.children: a.add(tree) else: empty = [] for tree in c.children: empty.append(-1 * tree.score) c.score = max(empty) h = [tree.score for tree in c.children] mini = min(h) minindex = h.index(mini) return c.value.get_possible_moves()[minindex]
class StackEmptyTestCase(unittest.TestCase): """Test behaviour of an empty Stack.""" def setUp(self): """Set up an empty stack.""" self.stack = Stack() def tearDown(self): """Clean up.""" self.stack = None def testIsEmpty(self): """Test is_empty() on empty Stack.""" # it's hard to avoid \ continuation here. assert self.stack.is_empty(), \ 'is_empty returned False on an empty Stack!' def testadd(self): """Test add to empty Stack.""" self.stack.add("foo") assert self.stack.remove() == "foo", \ 'Wrong item on top of the Stack! Expected "foo" here.'
def list_stack(list: list, stack: Stack) -> None: """ some function to use class stack >>> a2 = Stack() >>> list_stack([1, [3, [5, 7], 9], 11], a2) 11 9 7 5 3 1 """ for item in list: stack.add(item) while not stack.is_empty(): remove = stack.remove() if type(remove) == type(list): for thing in remove: stack.add(thing) else: print(remove)
def convertor(expression): expression = list(expression) postfix_exp = '' operator_precedence = {'-': 1, '+': 2, '*': 3, '/': 4} container = Stack() for symbol in expression: if symbol in operator_precedence: if not container.isEmpty() and container[-1] != '(': if operator_precedence[ container[-1]] >= operator_precedence[symbol]: postfix_exp += container[-1] container.remove() container.add(symbol) else: container.add(symbol) else: container.add(symbol) elif symbol == '(': container.add(symbol) elif symbol == ')' and not container.isEmpty(): while container[-1] != '(': postfix_exp += container[-1] container.remove() container.remove() else: postfix_exp += symbol while not container.isEmpty(): postfix_exp += container[-1] container.remove() return postfix_exp
def iterative_helper(game: Any, start: Any) -> List[int]: """ A helper for it_minimax, returns a list containing the score of the possible moves """ storage = [] s = Stack() s.add([Tree(start), None]) while not s.is_empty(): data = s.remove() if not game.is_over(data[0].value) and data[0].children == []: intermediate = [] for move in data[0].value.get_possible_moves(): intermediate.append( [Tree(data[0].value.make_move(move)), None]) s.add([Tree(data[0].value, intermediate), None]) for rest in intermediate: s.add(rest) elif game.is_over(data[0].value): game.current_state = data[0].value player = data[0].value.get_current_player_name() if game.is_winner(player): data[1] = 1 elif not game.is_winner(player) and not game.\ is_winner(opponent(player)): data[1] = 0 else: data[1] = -1 storage.append(data) else: num = [] for i in data[0].children: num += [x[1] * -1 for x in storage if i[0].value is x[0].value] data[1] = max(num) storage.append(data) final = [] for i in storage[-1][0].children: for data1 in storage: if i[0].value == data1[0].value: final.append(data1[1] * -1) return final
def minimax_iterative_strategy(game: Any) -> Any: """ Return a move for game through applying interactive minimax strategy. """ state = game.current_state moves = state.get_possible_moves() stack = Stack() stack.add([Tree(state), []]) box = [] while not stack.is_empty(): re = stack.remove() if re[0].value.get_possible_moves() != [] and re[0].children == []: lst = [] for move in re[0].value.get_possible_moves(): lst.append([Tree(re[0].value.make_move(move)), []]) stack.add([Tree(re[0].value, lst), []]) for l in lst: stack.add(l) elif game.is_over(re[0].value): game.current_state = re[0].value player = re[0].value.get_current_player_name() if game.is_winner(player): re[1] = 1 else: re[1] = -1 if game.is_winner('p1') or \ game.is_winner('p2') else 0 box.append(re) else: count = [] for i in re[0].children: count += [a[1] * -1 for a in box if a[0].value is i[0].value] re[1] = max(count) box.append(re) score = [] for i in box[-1][0].children: for itm in box: if i[0].value == itm[0].value: score.append(itm[1] * -1) if 1 in score: return moves[score.index(1)] elif 0 in score: return moves[score.index(0)] return moves[0]
def list_stack(st: Stack, lst: list) -> None: """ Add each element of lst to Stack, then remove it from the top and print it """ for element in lst: st.add(element) # for sth in st: # if type(sth) == list: # for e in sth: # st.add(e) while not st.is_empty(): # new =[] top = st.remove() st.add(top) if type(top) == list: st.remove() for item in top: st.add(item) # st.remove() print(st.remove())
def iterative_minimax_strategy(game: Any) -> Any: """ Minimax strategy done with a tree file structure and stacks """ old_game = copy.deepcopy(game) current_state = game.current_state root = Tree(current_state) stack = Stack() stack.add(root) while not stack.is_empty(): top = stack.remove() game.current_state = top.value if game.is_over(top.value): game.current_state = top.value if game.is_winner(top.value.get_current_player_name()): top.score = 1 game.current_state = old_game.current_state elif game.is_winner('p1') or game.is_winner('p2'): top.score = -1 game.current_state = old_game.current_state else: top.score = 0 game.current_state = old_game.current_state elif top.children == []: stack.add(top) for move in top.value.get_possible_moves(): new_state = top.value.make_move(game.str_to_move(str(move))) trees = Tree(new_state) trees.move = move top.children.append(trees) stack.add(trees) else: children_score = [] for child in top.children: children_score.append(child.score * -1) top.score = max(children_score) for child in root.children: if child.score * -1 == root.score: return child.move return old_game.current_state.get_possible_moves()[0]
def add(self, n: int) -> None: """Add n on top of self if it evenly divides its predecessor or self is empty. Otherwise, raise a ValueError and leave self as it was before. Precondition: Possibly empty self contains only Integers. >>> s = DividingStack() >>> s.push(12) >>> s.push(4) >>> # now s.push(3) should raise Exception. """ if self.is_empty(): Stack.add(self, n) else: item = self.remove() Stack.add(self, item) if item % n == 0: Stack.add(self, n) else: raise Exception()
9 7 5 3 1 """ for i in l: s.add(i) while not s.is_empty(): el = s.remove() if isinstance(el, list): for j in el: s.add(j) else: print(el) if __name__ == '__main__': import doctest doctest.testmod() s = Stack() imp = input('type a string: ') while not imp == 'end': s.add(imp) inp = input('type a string: ') while not s.is_empty(): print(s.remove()) list_stack([1, [3, [5, 7], 9], 11], Stack())
class StackEmptyTestCaseByProf(unittest.TestCase): """Test behaviour of an empty Stack.""" def setUp(self): """Set up an empty stack.""" self.s1 = Stack() self.s2 = Stack() def tearDown(self): """Clean up.""" self.s1 = None self.s2 = None def test_IsEmpty(self): """Test is_empty() on empty Stack.""" # it's hard to avoid \ continuation here. self.assertTrue(self.s1.is_empty()) def test_add(self): """Test add to empty Stack.""" self.s1.add("foo") self.assertTrue(self.s1.remove() == "foo") def test_equality(self): """test if two non-empty stack are equal""" self.s1.add("foo") self.s1.add("jijiji") self.s2.add("foo") self.s2.add("jijiji") self.assertTrue(self.s1 == self.s2) def test_not_equality(self): """test if two non-empty stack are equal""" self.s1.add("foo") self.s1.add("Joo") self.s2.add("Joo") self.s2.add("foo") self.assertFalse(self.s1 == self.s2)