def balanced_delimiters(s: str) -> bool: """ Return whether the delimiters in string s are balanced. Assume: Only delimiters are brackets, parentheses, braces >>> balanced_delimiters("[({])}") False >>> balanced_delimiters("[({})]]") False >>> balanced_delimiters("[[]") False >>> balanced_delimiters("[(){}]") True """ st = Stack() left_delim = {")": "(", "]": "[", "}": "{"} for c in s: if c not in "()[]{}": pass elif c in "([{": st.add(c) elif not st.is_empty(): assert c in ")]}" if left_delim[c] != st.remove(): return False else: return False pass return st.is_empty()
def iterative_minimax_strategy(game: Any)-> Any: """An iterative implementation of minimax strategy """ initial_root = Tree(game) stack_of_tree_games = Stack() stack_of_tree_games.add(initial_root) # in a loop, do the following (until the stack is empty): while not stack_of_tree_games.is_empty(): # get item at the top of the stack_of_games top = stack_of_tree_games.remove() # if the state of the item is over, set the Tree's score # the score is -1 for a loss, 0 for a draw, and 1 for a win if top.value.is_over(top.value.current_state): set_tree_score(top) # elif we haven't looked at this node (it has no children) elif top.children == []: # create new items, which are the result of # applying each possible move to the current state. # we store these children in a list for now w/ a helper function create_children(top) stack_of_tree_games.add(top) for child in top.children: stack_of_tree_games.add(child) else: # we've looked at this state before top.children is not None children_score = [(-1 * x.score) for x in top.children] top.score = max(children_score) best_score = initial_root.score for child in initial_root.children: if (-1 * child.score) == best_score: correct_resultant = child break return correct_resultant.move
def iterative_minimax_strategy(game: Any) -> Any: """ Return a move for game by iterative minimax strategy. """ s = Stack() id0 = 0 d = {0: Tree([id0, game, None])} s.add(0) while not s.is_empty(): id1 = s.remove() item = [id1] if d[id1].children == []: for move in d[id1].value[1].current_state.get_possible_moves(): game1 = copy.deepcopy(d[id1].value[1]) game1.current_state = game1.current_state.make_move(move) id0 += 1 d[id0] = Tree([id0, game1, None]) d[id1].children.append(id0) item.append(id0) else: item.extend(d[id1].children) for num in item: if d[num].value[1].is_over(d[num].value[1].current_state): d[num].value[2] = -1 elif d[num].children != [] and all(d[x].value[2] is not None for x in d[num].children): d[num].value[2] = max([(-1) * d[y].value[2] for y in d[num].children]) else: s.add(num) i = 0 for q in d[0].children: if d[q].value[2] == -1: i = d[0].children.index(q) return game.current_state.get_possible_moves()[i]