コード例 #1
0
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()
コード例 #2
0
ファイル: go.py プロジェクト: xiao-liu/zeta-go-legacy
    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
ファイル: go.py プロジェクト: xiao-liu/zeta-go-legacy
    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
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)