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 __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() # self.waiting.debug_print() # self.waiting.add('a') # self.waiting.add('b') # self.waiting.add('c') # self.waiting.debug_print() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs)
def evaluate(expression): # trivial cases if not expression: return 0 operands = { '+': (lambda x, y: x + y), '-': (lambda x, y: x - y), '*': (lambda x, y: x * y), '/': (lambda x, y: x // y) } stack = Stack() # convert the incoming string to an array exp = expression.split(',') # iterate through each exp for e in exp: if e in operands: # if operand, pop two numbers and calculate a b . p1 = stack.pop() p2 = stack.pop() res = operands[e](p2, p1) stack.push(res) else: # else push the number onto stack val = int(e) stack.push(val) final_res = stack.pop() return final_res
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: """ 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]
class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def tearDown(self): del self.stack def test_push(self): self.stack.push('A') value = self.stack.get(0) self.assertEqual(value, 'A') def test_pop(self): self.stack.push('A') self.stack.push('B') value = self.stack.pop() self.assertEqual(value, 'B')
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() # self.waiting.debug_print() # self.waiting.add('a') # self.waiting.add('b') # self.waiting.add('c') # self.waiting.debug_print() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' for index, line in enumerate(f): line = line.rstrip() print('{}:{}'.format(index, line)) parts = line.split(',') # try: func = getattr(self, '{}'.format(parts[0].lower())) func(*parts[1:]) # except Exception as e: # print('Error: {}'.format(e)) # split and handle the commands here def debug(self, *args): self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print() def song(self, *args): print(self.songs_iter.next()) def appetizer(self, *args): try: print("{} >>> {}".format( self.appetizers.dequeue(), ', '.join([str(item) for item in self.waiting.getLastThree()]))) except Exception as e: print('Error:', e) def appetizer_ready(self, *args): self.appetizers.enqueue(args[0]) def seat(self, *args): self.buzzers.push('Buzzer') print(self.waiting.get(0)) self.waiting.delete(0) def call(self, *args): self.callahead.add(args[0]) def arrive(self, *args): if (self.callahead.deleteByValue(args[0]) == True): self.waiting.insert(self.getFiveIn(self.waiting.size), args[0]) else: sws = self.waiting.size self.waiting.insert(sws if sws >= 0 else 0, args[0]) self.buzzers.pop() def leave(self, *args): self.waiting.deleteByValue(args[0]) self.buzzers.push('Buzzer') def getFiveIn(self, size): return size - 4 if size - 4 >= 0 else 0
def shortest_equivalent_path(path): stack = Stack() # append '/' onto the stack stack.push('/') # split the path on the basis of '/' path_names = path.split('/') for name in path_names: if (len(name) != 0 and name != '.'): # ignore '.' and '' if (name == '..'): # pop from the stack if (stack.top() == '/' or stack.top() == '..'): # if there's no dir push .. onto the stack stack.push(name) else: dir_ = stack.pop() else: stack.push(name) new_path = '' val = stack.pop() while (val != '/'): new_path = val + '/' + new_path val = stack.pop() # if initial path starts with '/' then push that onto the new_path if (path[0] == '/'): return val + new_path[:-1] return new_path[:-1]
def setUp(self): self.stack = Stack()
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' for line_i, line in enumerate(f): line = line.rstrip() # split and handle the commands here print('{}:{}'.format(line_i, line)) parts = line.split(',') try: func = getattr(self, 'cmd_{}'.format(parts[0].lower())) func(*parts[1:]) except Exception as e: print('Error: {}'.format(e)) def cmd_appetizer(self, *args): wait = [] r = self.waiting._get_node(self.waiting.size - 1) i = 0 try: if self.waiting.size > 3: i = self.waiting.size - 3 for x in range(self.waiting.size, i,-1): wait.append(str(r.value)) r = r.prev print('{} >>> {}'.format(self.appetizers.dequeue(), ', '.join(wait))) except: raise IndexError('The given index is not within the bounds of the current list.') def cmd_appetizer_ready(self, *args): self.appetizers.enqueue(args[0]) def cmd_call(self, *args): self.callahead.add(args[0]) def cmd_arrive(self, *args): if (self.callahead.check_value(args[0])): if self.waiting.size > 5: self.waiting.insert(self.waiting.size - 4, args[0]) index = self.callahead.check_index(args[0]) self.callahead.delete(index) else: self.waiting.insert(0, args[0]) index = self.callahead.check_index(args[0]) self.callahead.delete(index) else: self.waiting.add(args[0]) self.buzzers.pop() def cmd_leave(self, *args): self.buzzers.push('Buzzer') index = self.waiting.check_index(args[0]) self.waiting.delete(index) def cmd_seat(self, *args): if self.waiting.size != 0: self.buzzers.push('Buzzer') next_party = self.waiting._get_node(0) print(next_party.value) self.waiting.delete(0) else: raise IndexError('The given index is not within the bounds of the current list.') def cmd_debug(self, *args): self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print() def cmd_song(self, *args): val = self.songs_iter.next() print(val)
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' self.songs.debug_print() for line_i, line in enumerate(f): line = line.rstrip() comms = line.split(',') print('%d:%s' % (line_i, line)) if comms[0] == 'SEAT': print('SEAT >>>>', line) elif comms[0] == 'APPETIZER': wait_iter = DoublyLinkedListIterator(self.waiting) while wait_iter.has_next(): wait_iter.next() count = 0 person_array = [] try: food = self.appetizers.dequeue() except: print('error') while wait_iter.has_prev() and count < 3: person_array.append(wait_iter.node.value) count += 1 print('%s >>> %s' % (food, ', '.join(person_array))) elif comms[0] == 'SONG': self.songs_iter.next() print(self.songs_iter.node.value) elif comms[0] == 'LEAVE': self.waiting.delete(comms[1]) elif comms[0] == 'DEBUG': self.debug() elif comms[0] == 'ARRIVE': self.waiting.add(comms[1]) try: self.callahead.delete(comms[1]) except ValueError('error'): continue elif comms[0] == 'CALL': self.callahead.add(comms[1]) elif comms[0] == 'APPETIZER_READY': self.appetizers.enqueue(comms[1]) else: print("ERROR!!!!!", line) # split and handle the commands here def debug(self): '''print all objects''' self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print()
def test_stack_pop(self): s = Stack() s.push('a') s.push('b') s.push('c') self.assertEqual(s.pop(), 'c')
def test_stack_push(self): s = Stack() s.push('a') s.push('b') s.push('c') self.assertEqual(s.size, 3)
def test_stack_create(self): s = Stack() self.assertEqual(s, s)
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' for line_i, line in enumerate(f): line = line.rstrip() # split and handle the commands here print('{}:{}'.format(line_i, line)) parts = line.split(',') # call this command's function try: func = getattr(self, 'cmd_{}'.format(parts[0].lower())) func(*parts[1:]) except Exception as e: print('Error: {}'.format(e)) def cmd_debug(self, *args): self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print() def cmd_song(self, *args): print(self.songs_iter.next()) def cmd_appetizer(self, *args): app = self.appetizers.dequeue() i = self.waiting.size - 1 values = [] if self.waiting.size >= 3: while i >= self.waiting.size - 3: values.append(self.waiting.get(i)) i -= 1 elif self.waiting.size == 2: while i >= self.waiting.size - 2: values.append(self.waiting.get(i)) i -= 1 elif self.waiting.size == 1: while i >= self.waiting.size - 1: values.append(self.waiting.get(i)) i -= 1 else: values.append(self.waiting.get(i)) print('{} >>> {}'.format(app, ', '.join(values))) def cmd_appetizer_ready(self, *args): self.appetizers.enqueue(args[0]) def cmd_call(self, *args): self.callahead.add(args[0]) def cmd_arrive(self, *args): # check if they were on the callin list callaheadSize = self.callahead.size waitingSize = self.waiting.size callahead = False self.buzzers.pop() i = 0 while i < callaheadSize: if self.callahead.get(i) == args[0]: self.callahead.delete(i) callahead = True break i += 1 if callahead: if waitingSize <= 5: self.waiting.insert(0, args[0]) else: self.waiting.insert(waitingSize - 4, args[0]) else: self.waiting.add(args[0]) def cmd_seat(self, *args): try: print(self.waiting.get(0)) self.waiting.delete(0) self.buzzers.push('Buzzer') except: raise IndexError( 'The given index is not within the bounds of the current list.' ) def cmd_leave(self, *args): self.buzzers.push('Buzzer') waitingSize = self.waiting.size i = 0 while i < waitingSize: if self.waiting.get(i) == args[0]: self.waiting.delete(i) break i += 1