Пример #1
0
class TestQueue(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.initial_list = [i for i in range(5)]

    @classmethod
    def tearDownClass(self):
        print("All tests for queue completed")

    def setUp(self):
        # print("Initializing queue")
        self.queue = Queue(8, 0, initial_iter=self.initial_list)

    def tearDown(self):
        pass

    def test_head(self):
        """
        Test getting top element        
        """
        self.assertEqual(4, self.queue.head())

    def test_tail(self):
        """
        Test getting top element        
        """
        self.assertEqual(0, self.queue.tail())

    def test_enqueue(self):
        """
        Test pushing to stack top
        """
        self.queue.enqueue(5)
        self.assertEqual(5, self.queue.tail())
        self.assertNotEqual(5, self.queue.head())
        self.assertEqual(4, self.queue.head())
        self.assertEqual(6, self.queue.size())

    def test_dequeue(self):
        """
        Test popping
        """
        for x in range(4, -1, -1):
            self.assertEqual(x, self.queue.dequeue())

        self.assertEqual(0, self.queue.size())
Пример #2
0
    def update_empty_intersection(self):
        n = self.board_size * self.board_size
        ownership = [UNDECIDED] * n
        visited = BitSet(n)
        adjacent_chains = BitSet(n)
        for x in range(self.board_size):
            for y in range(self.board_size):
                z = x * self.board_size + y
                if self._color[z] != EMPTY or visited.contains(z):
                    continue

                self._chain_size[z] = 0
                adjacent_to_black, adjacent_to_white = False, False
                adjacent_chains.clear()

                q = Queue(n)
                q.enqueue((x, y))
                visited.add(z)
                while not q.is_empty():
                    x, y = q.dequeue()
                    for dx, dy in _directions:
                        if self.on_board(x + dx, y + dy):
                            if self.color(x + dx, y + dy) == BLACK:
                                adjacent_chains.add(self.find(x + dx, y + dy))
                                adjacent_to_black = True
                            elif self.color(x + dx, y + dy) == WHITE:
                                adjacent_chains.add(self.find(x + dx, y + dy))
                                adjacent_to_white = True
                            elif not visited.contains(
                                (x + dx) * self.board_size + y + dy):
                                q.enqueue((x + dx, y + dy))
                                visited.add((x + dx) * self.board_size + y +
                                            dy)
                    self._parent[x * self.board_size + y] = z
                    self._chain_size[z] += 1

                if (adjacent_to_black and adjacent_to_white) \
                        or len(adjacent_chains) == 0:
                    ownership[z] = UNDECIDED
                elif len(adjacent_chains) == 1:
                    if adjacent_to_black:
                        ownership[z] = BLACK_EYE
                    else:
                        ownership[z] = WHITE_EYE
                else:
                    if adjacent_to_black:
                        ownership[z] = BLACK_OWNED
                    else:
                        ownership[z] = WHITE_OWNED

        return ownership
Пример #3
0
    def _remove(self, x, y):
        self._liberties[self.find(x, y)] = None

        n = self.board_size * self.board_size
        z = x * self.board_size + y
        color = self._color[z]

        # insert (x, y) into the queue, and mark it as "visited but not
        # processed" (color = _GRAY)
        # we abuse the _color array to store the BFS state here:
        #   - color = EMPTY: processed
        #   - color = BLACK: not visited (for black stones)
        #   - color = WHITE: not visited (for white stones)
        #   - color = _GRAY: visited (i.e., in queue) but not processed
        q = Queue(n)
        q.enqueue((x, y))
        self._color[z] = _GRAY
        adjacent_opponent_chains = SmallSet(4)
        while not q.is_empty():
            x, y = q.dequeue()
            adjacent_opponent_chains.clear()
            for dx, dy in _directions:
                if self.on_board(x + dx, y + dy):
                    # insert all the own adjacent stones that are not
                    # visited into the queue
                    if self.color(x + dx, y + dy) == color:
                        q.enqueue((x + dx, y + dy))
                        self._color[(x + dx) * self.board_size + y +
                                    dy] = _GRAY
                    # save opponent's stone chains that are adjacent to
                    # this new empty intersection
                    if self.color(x + dx, y + dy) == -color:
                        adjacent_opponent_chains.add(self.find(x + dx, y + dy))
            # the new empty intersection (x, y) provides liberty to its
            # adjacent stone chains
            z = x * self.board_size + y
            for c in adjacent_opponent_chains:
                if self._liberties[c] is None:
                    self._liberties[c] = BitSet(n)
                self._liberties[c].add(z)
            self._color[z] = EMPTY
Пример #4
0
def bfs(initial, goal_test, successors):
    frontier = Queue()
    frontier.push(Node(initial))
    explored = {initial}

    while not frontier.empty:
        node: Node = frontier.pop()

        if goal_test(node.state):
            return node

        for parent in successors(node.state):
            if parent in explored:
                continue

            explored.add(node.state)
            frontier.push(Node(parent, node))
    return None
Пример #5
0
 def setUp(self):
     # print("Initializing queue")
     self.queue = Queue(8, 0, initial_iter=self.initial_list)
Пример #6
0
 def __init__(self, conf):
     self._regret_frac = conf.RESIGN_REGRET_FRAC
     self._histories = Queue(conf.NUM_RESIGN_SAMPLES)
     self._threshold = -1.0
Пример #7
0
class ResignManager:
    def __init__(self, conf):
        self._regret_frac = conf.RESIGN_REGRET_FRAC
        self._histories = Queue(conf.NUM_RESIGN_SAMPLES)
        self._threshold = -1.0

    def threshold(self):
        return -1.0 if not self._histories.is_full() else self._threshold

    def add(self, history, result):
        if len(history) == 0:
            return

        # suppose the resignation values of a game are
        # [v_0, v_1, v_2, ...], we say time t is resignation eligible
        # if it is possible to choose an appropriate threshold such
        # that the game resigns at t
        # for example, t = 0 is always resignation eligible
        # t = 1 is resignation eligible if and only if v_1 < v_0,
        # otherwise it is impossible to find a threshold such that the
        # game resigns at t = 1
        # it is not difficult to see that if t is resignation eligible,
        # the next resignation eligible time is the smallest t' such
        # that t' > t and v_t' < v_t

        # keep only the resignation eligible time and discard the rest
        history_ = [history[0]]
        for t in range(1, len(history)):
            if history[t][0] < history_[-1][0]:
                history_.append(history[t])

        # update the regret
        # regret = 1 means a false positive resignation, i.e., the game
        # could have been won if the player had not resigned
        # regret = 0 otherwise
        for i in range(len(history_)):
            # history_[i][1] originally stores the player
            # after regret is calculated, the player information is no
            # longer needed, we reuse the space to store regret
            history_[i][1] = 1 if history_[i][1] == result else 0

        # discard the earliest history and save the current history
        if self._histories.is_full():
            self._histories.dequeue()
        self._histories.enqueue(history_)

        # update the threshold when we get sufficient samples
        if self._histories.is_full():
            self._update_threshold()

    def _update_threshold(self):
        # sort all the resignation values in descending order
        resign_values = []
        for history in self._histories:
            resign_values += [x[0] for x in history]
        resign_values = sorted(resign_values, reverse=True)

        # search for the threshold
        pointers = [0] * len(self._histories)
        i = 0
        while i < len(resign_values):
            threshold = resign_values[i]

            # calculate the number of regretful resignations for this
            # candidate threshold
            regrets = 0
            for j in range(len(self._histories)):
                history = self._histories[j]
                while pointers[j] < len(history) and \
                        history[pointers[j]][0] > threshold:
                    pointers[j] += 1
                if pointers[j] < len(history):
                    regrets += history[pointers[j]][1]

            if regrets <= self._regret_frac * len(self._histories):
                self._threshold = threshold
                return

            # find the next candidate threshold
            j = i + 1
            while j < len(resign_values) and \
                    resign_values[j] == resign_values[i]:
                j += 1
            i = j

        self._threshold = -1.0
Пример #8
0
 def __init__(self):
     self.stack = Stack()
     self.queue = Queue()
     self.meccaMap = MaccaMap()
     self.start_place = self.meccaMap.set_starting_place()
     self.target_place = self.meccaMap.set_target_place()
Пример #9
0
class FindRoute:
    """a class to find route between 2 cities using depth first search"""
    def __init__(self):
        self.stack = Stack()
        self.queue = Queue()
        self.meccaMap = MaccaMap()
        self.start_place = self.meccaMap.set_starting_place()
        self.target_place = self.meccaMap.set_target_place()

    def printNodes(self, queue):
        print('-------------- Nodes --------------')
        print()
        for node in queue:
            print(node['name'], ', ')
        print()

    def depth_first_search(self):
        """travel form start_place to target_place from left to right while logging the traveled cities"""
        global steps, times
        current_step = 0
        time0 = time.time()

        visited_places = []
        print("----------Depth First Search Traverse-------------")
        self.stack.unique_push(self.start_place)

        while not self.stack.is_empty():
            current_step += 1
            current_place = self.stack.pop()
            visited_places.append(current_place)
            print("I am at", current_place, "place")
            self.stack.display()
            print("Visited cities are:", visited_places)
            if current_place == self.target_place:
                print("I have reached the target place")

                time1 = time.time()
                time_differnce = time1 - time0
                times.append(time_differnce)
                steps.append(current_step)

                break
            else:
                connected_nodes = self.meccaMap.graph.get_children_of_node(
                    current_place)

                print("The connected nodes are:")
                print()
                self.printNodes(connected_nodes)
                for node in connected_nodes:
                    # push to stack if not visited and not in stack
                    if node['name'] not in visited_places:
                        self.stack.unique_push(node['name'])
                        # print(node, "has been added to stack")

                self.stack.display()
            print("-----------------------------------------")
        else:
            # executed if target not found(break statement not executed)
            print("I wasn't able to find a route")

    def breadth_first_search(self):
        """travel form start_place to target_place from left to right breadth first while logging the traveled cities"""
        global steps, times
        current_step = 0
        time0 = time.time()

        visited_places = []
        print("----------Breadth First Search Traverse-------------")
        self.queue.unique_enqueue(self.start_place)

        while not self.queue.is_empty():
            current_step += 1
            current_place = self.queue.dequeue()
            visited_places.append(current_place)
            print("I am at", current_place, "place")
            self.queue.display()
            print("Visited places are:", visited_places)
            if current_place == self.target_place:
                print("I have reached the target place")

                time1 = time.time()
                time_differnce = time1 - time0
                times.append(time_differnce)
                steps.append(current_step)

                break
            else:
                connected_nodes = self.meccaMap.graph.get_children_of_node(
                    current_place)

                print("The connected nodes are:")
                print()
                self.printNodes(connected_nodes)

                for node in connected_nodes:
                    # push to stack if not visited and not in stack
                    if node['name'] not in visited_places:
                        self.queue.unique_enqueue(node['name'])
                        # print(node, "has been added to stack")

                self.queue.display()
            print("-----------------------------------------")
        else:
            # executed if target not found(break statement not executed)
            print("I wasn't able to find a route")

    def greedy_first_search(self):
        global steps, times
        current_step = 0
        time0 = time.time()

        visited = complate_path = ['']
        current_place = visited[0] = complate_path[0] = self.start_place

        while current_place is not self.target_place:
            connected_nodes = self.meccaMap.graph.get_children_of_node(
                current_place)
            queue = sorted(connected_nodes, key=lambda i: i['distance'])
            self.printNodes(queue)
            for place in queue:
                current_step += 1
                first_in_queue = queue.pop(0)['name']
                print('remove ', first_in_queue, 'from queue..')
                print()

                # connected nodes to the first element in queue which we just pop-ed up
                connected_nodes_to_first = sorted(
                    self.meccaMap.graph.get_children_of_node(first_in_queue),
                    key=lambda i: i['distance'])

                for place in connected_nodes_to_first:
                    if place['name'] == self.target_place:
                        complate_path.append(first_in_queue)
                        complate_path.append(place['name'])
                        print("I have reached the target place")

                        time1 = time.time()
                        time_differnce = time1 - time0
                        times.append(time_differnce)
                        steps.append(current_step)

                        return complate_path

                # connected nodes to the first element in queue which we just pop-ed up, but filtered from visited places to add them to the queue
                connected_nodes_filtered = [
                    i for i in connected_nodes_to_first
                    if i['name'] not in visited
                ]

                queue.extend(connected_nodes_filtered)
                self.printNodes(queue)
 def __init__(self):
     """
     Initialize your data structure here.
     """
     self.input_queue = Queue()
     self.output_queue = Queue()
class MyStack(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.input_queue = Queue()
        self.output_queue = Queue()

    def push(self, x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: None
        """
        self.input_queue.push(x)

    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        size = self.input_queue.size()
        if size == 0:
            return None
        for i in range(size - 1):
            self.output_queue.push((self.input_queue.pop()))
        item = self.input_queue.pop()
        self.input_queue, self.output_queue = self.output_queue, self.input_queue

        return item

    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        size = self.input_queue.size()
        if size == 0:
            return None
        for i in range(size - 1):
            self.output_queue.push((self.input_queue.pop()))
        item = self.input_queue.peek()
        self.output_queue.push((self.input_queue.pop()))
        self.input_queue, self.output_queue = self.output_queue, self.input_queue
        return item

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        return self.input_queue.is_empty()
Пример #12
0
class Game():
    def __init__(self):
        tm.Living.spawn()

    scoring = {0: 0, 1: 40, 2: 100, 3: 300, 4: 1200}
    score = 0

    s = Stack()
    q = Queue()
    holding_bag = Queue()

    GRAY = (150, 150, 150)
    DGRAY = (80, 80, 80)
    WHITE = (255, 255, 255)
    CYAN = (0, 255, 255)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    ORANGE = (255, 165, 0)
    YELLOW = (255, 255, 0)
    PURPLE = (148, 0, 211)

    pg.font.init()
    fontSize = 25
    main_font = pg.font.SysFont("arial", fontSize)
    BoardHeight, BoardWidth = 20, 10
    WIDTH, HEIGHT = 600, 800
    PrevXPadd, PrevYPadd = 160, 140
    zoom = 40
    start = timeit.default_timer()
    times = 0
    run = True
    end = False

    @classmethod
    def hold(cls, curr):
        if cls.times == 1:
            if len(cls.holding_bag) != 0:
                curr.x, curr.y, curr.ghost.x = 3, 0, 3
                cls.q.add(cls.holding_bag.current())
                cls.holding_bag.add(curr)
            else:  # if empty
                curr.x, curr.y, curr.ghost.x = 3, 0, 3
                cls.holding_bag.add(curr)
                tm.Living.spawn()

    @classmethod
    def update_window(cls, win):
        win.fill((0, 0, 0))
        cls.run_board(win)
        current = cls.q.current()
        cls.preview(current, win, active_tetro=True)
        cls.preview(current.ghost, win, active_tetro=True)

        for m, n in enumerate(range(1, 4)):
            cls.preview(tm.Tetromino(cls.s.peek(n=n)[m]),
                        win, cls.WIDTH - cls.PrevXPadd,
                        cls.PrevYPadd * n * (0.3 * n))

        if len(cls.holding_bag) != 0:
            cls.preview(cls.holding_bag.current(), win,
                        cls.WIDTH - cls.PrevXPadd, cls.HEIGHT - 200)
        else:
            cls.rect(win, cls.DGRAY, cls.WIDTH - cls.PrevXPadd,
                     cls.HEIGHT - 200)

        score_text = Game.main_font.render("Score = {}".format(Game.score), 1,
                                           Game.WHITE)

        win.blit(score_text,
                 ((Game.BoardWidth * Game.zoom), score_text.get_height()))

        pg.display.update()

    @classmethod
    def run_board(cls, win):
        for i in range(cls.BoardHeight):
            for j in range(cls.BoardWidth):
                if tm.Tetromino.board_matrix[i][j] == 0:
                    color = cls.GRAY
                    border = 1
                else:
                    color = tm.Tetromino.colors[tm.Tetromino.board_matrix[i]
                                                [j]]
                    border = 0

                pg.draw.rect(win, color,
                             [j * cls.zoom, i * cls.zoom, cls.zoom, cls.zoom],
                             border)

    @classmethod
    def clear_board(cls):
        def end():
            # if any letters present at the top
            if any(tm.Tetromino.board_matrix[0]):
                return True

        # If all elements in board_matrix's row are != 0, clear them
        update = [tm.Tetromino.board_matrix[i] for i in range(cls.BoardHeight) \
                                    if not all(tm.Tetromino.board_matrix[i])]

        before_clean = len(tm.Tetromino.board_matrix)
        after_clean = len(update)
        clear_amount = before_clean - after_clean

        cls.score += cls.scoring[clear_amount]

        for _ in range(clear_amount):
            update[:0] = [[0 for _ in range(cls.BoardWidth)]]

        tm.Tetromino.board_matrix = update

        if end() and not cls.end:
            cls.end = True
            db.update_db(cls.score)
            cls.run = False

    @classmethod
    def rect(
        cls,
        win,
        color,
        x=1,
        y=1,
        j_mult=1,
        i_mult=1,
    ):
        pg.draw.rect(win, color, [
            x + (j_mult * cls.zoom), y +
            (i_mult * cls.zoom), cls.zoom - 1, cls.zoom - 1
        ])

    @staticmethod
    def delta_t():
        x = lambda a: eval("%.{}f".format(1) % a)
        if x(timeit.default_timer() - Game.start) % 1 == 0:
            Game.start -= 0.1
            return True

    @staticmethod
    def preview(current, win, x=1, y=1, active_tetro=False):
        for i in range(4):
            for j in range(4):
                temp = i * 4 + j
                if temp in current.current_shape():
                    if not active_tetro:
                        Game.rect(win, current.color, x, y, j, i)
                    else:
                        Game.rect(win,
                                  current.color,
                                  j_mult=current.x + j,
                                  i_mult=current.y + i)
Пример #13
0
    def _level_order_traversal(self, starting_node=None, include_none=True):
        """
        Traverses the binary tree from top level to bottom and saves data/height/depth for testing purpose

        Args:
            starting_node (TreeNode): traverse the subtree rooted at given starting node
            include_none (bool): True if including None node in binary tree

        Returns:
            data_array ([3-tuple]): [(data saved in node, height, depth)]
        """
        data_array = []

        # returns empty list if the binary tree is empty
        if self._root is None:
            return data_array

        # traverse from root if starting node is not given
        if starting_node is None:
            starting_node = self._root

        queue = Queue()
        # (data, height, depth, left child, right child)
        queue.enqueue((starting_node.data(), starting_node.height(),
                       starting_node.depth(), starting_node.left_child(),
                       starting_node.right_child()))

        while not queue.empty():
            top_node = queue.dequeue()

            if top_node[0] is not None:
                # if it's a non-trival node, append data/height/depth
                data_array.append((top_node[0], top_node[1], top_node[2]))
            else:
                data_array.append(None)

            # if the node is not on the deepest level, left and right child can be added into queue and visited soon
            if top_node[2] < self.depth():
                top_node_left_child, top_node_right_child = top_node[
                    3], top_node[4]

                entry = [None, top_node[1] - 1, top_node[2] + 1, None, None]
                if top_node_left_child is not None:
                    entry[0] = top_node_left_child.data()
                    entry[3] = top_node_left_child.left_child()
                    entry[4] = top_node_left_child.right_child()
                queue.enqueue(tuple(entry))

                entry = [None, top_node[1] - 1, top_node[2] + 1, None, None]
                if top_node_right_child is not None:
                    entry[0] = top_node_right_child.data()
                    entry[3] = top_node_right_child.left_child()
                    entry[4] = top_node_right_child.right_child()
                queue.enqueue(tuple(entry))

        # if include_none == False, filter out the None element
        if not include_none:
            data_array = list(filter(lambda x: x is not None, data_array))

        # remove all None at the end of list since they are trival and not informative
        while data_array[-1] is None:
            data_array.pop()

        return data_array