예제 #1
0
 def __init__(self):
     """
     Initialize your data structure here.
     """
     self._stack_in = Stack()
     self._stack_out = Stack()
     self._front = None
예제 #2
0
 def pre_order(tree):
     result = []
     s = Stack()
     s.add(tree)
     while not s.is_empty():
         t = s.pop()
         result.append(t.root)
         if t.right:
             s.add(t.right)
         if t.left:
             s.add(t.left)
     return result
예제 #3
0
def topologicalSort(dag):
    ''' Return a list containing a linear order
        of the given directed acyclic graph;
        Input should be an adjacency list;
    '''
    adjacencyList = dag.getAdjacencyList()
    linearOrder = []
    nextNodes = Stack()

    indegree = {}
    for node in adjacencyList:
        for neighbour in adjacencyList[node]:
            if neighbour in indegree:
                indegree[neighbour] += 1
            else:
                indegree[neighbour] = 1
    
    for node in adjacencyList:
        if node not in indegree:
            indegree[node] = 0
            nextNodes.push(node)

    while nextNodes.getSize() > 0:
        nextNode = nextNodes.pop()
        linearOrder.append(nextNode)
        for neighbour in adjacencyList[nextNode]:
            indegree[neighbour] -= 1
            if indegree[neighbour] == 0:
                nextNodes.push(neighbour)

    return linearOrder
예제 #4
0
    def postorder_traversal(self, starting_node=None):
        """
        Traverses the binary tree in post-order: left child -> right child -> parent node

        Args:
            starting_node (TreeNode): traverse the subtree rooted at given starting node

        Returns:
            data_array (list): list of data saved in binary tree
        """
        data_array = []

        if self._root is None:
            return data_array

        if starting_node is None:
            starting_node = self._root

        stack = Stack()
        current_node = starting_node
        stack.push(current_node)

        while not stack.empty():
            top_node = stack.top()
            if top_node != current_node.parent():
                self._to_highest_leftmost_leaf(stack)
            current_node = stack.pop()
            data_array.append(current_node.data())

        return data_array
예제 #5
0
 def last_order(tree):
     """
     通过镜像的前序遍历
     :param tree:
     :return:
     """
     result = []
     s = Stack()
     s.add(tree)
     while not s.is_empty():
         t = s.pop()
         result.append(t.root)
         if t.left:
             s.add(t.left)
         if t.right:
             s.add(t.right)
     result.reverse()
     return result
예제 #6
0
    class QueueByStack:
        def __init__(self):
            self.stack_in = Stack()
            self.stack_out = Stack()

        def put(self, element):
            self.stack_in.add(element)

        def get(self):
            if not self.stack_out.is_empty():
                return self.stack_out.pop()
            elif not self.stack_in.is_empty():
                while not self.stack_in.is_empty():
                    self.stack_out.add(self.stack_in.pop())
                return self.stack_out.pop()
            else:
                print('queue is empty')
                return None
예제 #7
0
    class StackWithMin(Stack):
        def __init__(self):
            super().__init__()
            self.min_stack = Stack()

        def add(self, e):
            super().add(e)
            if self.min_stack.is_empty():
                self.min_stack.add(e)
            else:
                if self.min_stack.get_top() > e:
                    self.min_stack.add(e)

        def pop(self):
            top = self.pop()
            if top == self.min_stack.get_top():
                self.min_stack.pop()
            return top

        def get_min(self):
            return self.min_stack.get_top()
예제 #8
0
    def inorder_traversal(self, starting_node=None):
        """
        Traverse the binary tree in in-order: left child -> parent node -> right child

        Args:
            starting_node (TreeNode): traverse the subtree rooted at given starting node

        Returns:
            data_array (list): list of data saved in binary tree
        """
        data_array = []

        if starting_node is None:
            starting_node = self._root

        stack = Stack()
        current_node = starting_node

        while True:

            while current_node is not None:
                stack.push(current_node)
                # always go along left child
                current_node = current_node.left_child()

            if stack.empty():
                break

            current_node = stack.pop()
            data_array.append(current_node.data())
            current_node = current_node.right_child()

        return data_array
예제 #9
0
 def isValid(self, s):
     """
     :type s: str
     :rtype: bool
     """
     stack = Stack()
     lookup = {')': '(', ']': '[', '}': '{'}
     for c in s:
         if c not in lookup:
             stack.push(c)
         elif stack.is_empty() or stack.pop() != lookup[c]:
             return False
     return stack.is_empty()
예제 #10
0
class TestStack(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.initial_list = [i for i in range(5)]

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

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

    def tearDown(self):
        pass

    def test_top(self):
        """
        Test getting top element        
        """
        self.assertEqual(4, self.stack.top())

    def test_push(self):
        """
        Test pushing to stack top
        """
        self.stack.push(5)
        self.assertEqual(5, self.stack.top())

    def test_pop(self):
        """
        Test popping
        """
        self.stack.push(5)
        self.assertEqual(5, self.stack.top())
        self.assertEqual(6, len(self.stack))

        for x in range(5, -1, -1):
            self.assertEqual(x, self.stack.pop())

        self.assertEqual(0, self.stack.size())
예제 #11
0
    def escape_room(self, room_id):
        ok = False
        
        if self.use_stack:
            q = Stack()
        else:
            q = Queue()

        cur_ent = self.entrance[room_id]
        cur_room = self.rooms[room_id]
        q.push(cur_ent)

        while(not q.empty()):
            if ok:
                break
            
            cur = q.pop()                        
            
            w,h = cur.width, cur.height
            p = cur.path

            cur_points = []
            for i in range(len(self.dir)):
                dw, dh = self.dir[i]
                dp = self.dir_str[i]
                cur_points.append(Point(w+dw, h+dh, p+dp))
                
            for i in range(len(cur_points)):
                cur_cand = cur_points[i]
                if(self.check(cur_cand, room_id)):
                    if(cur_room[cur_cand.height][cur_cand.width] == 'O' or
                       cur_room[cur_cand.height][cur_cand.width] == 'T'):
                        ok = True
                        self.add_path(cur_cand, room_id,
                                      len(self.rooms[room_id]), len(self.rooms[room_id][0]))
                        break
                    cur_room[cur_cand.height][cur_cand.width] = 'x'
                    q.push(cur_points[i])

        return ok
예제 #12
0
def build_prase_tree(expression):
    ex_list = list(expression)
    stack = Stack()
    bin_tree = BinaryTree('root')
    for i in ex_list:
        if i == '(':
            stack.push(bin_tree)
            bin_tree.insert_left_child('-')
            bin_tree = bin_tree.left_child
        elif i in '+-*/':
            bin_tree = stack.pop()
            bin_tree.set_root_val(i)
            bin_tree.insert_right_child('')
            stack.push(bin_tree)
            bin_tree = bin_tree.right_child
        elif i == ')':
            bin_tree = stack.pop()
        elif i not in '+-*/':
            bin_tree.set_root_val(i)
        else:
            raise ValueError
    return bin_tree
예제 #13
0
 def in_order(tree):
     result = []
     s = Stack()
     t = tree
     while 1:
         while t:
             s.add(t)
             t = t.left
         if not s.is_empty():
             t = s.pop()
             result.append(t.root)
             t = t.right
         else:
             break
     return result
예제 #14
0
파일: game.py 프로젝트: Valphai/Tetris
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)
예제 #15
0
class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self._stack_in = Stack()
        self._stack_out = Stack()
        self._front = None

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        if self._stack_in.is_empty():
            self._front = x
        self._stack_in.push(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if self.empty():
            return None
        if self._stack_out.is_empty():
            size = self._stack_in.size()
            for i in range(size):
                self._stack_out.push(self._stack_in.pop())
        return self._stack_out.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        if self.empty():
            return None
        if self._stack_out.is_empty():
            return self._front
        else:
            return self._stack_out.peek()

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return self._stack_in.is_empty() and self._stack_out.is_empty()
예제 #16
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()
예제 #17
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)
예제 #18
0
 def setUp(self):
     # print("Initializing stack")
     self.stack = Stack(8, 0, initial_iter=self.initial_list)
예제 #19
0
class FindRoute:
    """a class to find route between 2 cities using depth first search"""
    graph = Graph()
    stack = Stack()
    start_city = None
    target_city = None

    def __init__(self):
        self.setup_graph()
        self.set_starting_city()
        self.set_target_city()
        self.depth_first_search()

    def setup_graph(self):
        self.graph.add_node("Buraydah",
                            ["Unayzah", "Riyadh-Alkhabra", "Al-Bukayriyah"])
        self.graph.add_node("Unayzah", ["AlZulfi", "Al-Badai", "Buraydah"])
        self.graph.add_node("Riyadh-Alkhabra", ["Buraydah", "Al-Badai"])
        self.graph.add_node("Al-Bukayriyah", ["Buraydah", "Sheehyah"])
        self.graph.add_node("AlZulfi", ["Unayzah", "UmSedrah"])
        self.graph.add_node("Al-Badai",
                            ["Unayzah", "Riyadh-Alkhabra", "AlRass"])
        self.graph.add_node("Sheehyah", ["Al-Bukayriyah", "Dhalfa"])
        self.graph.add_node("UmSedrah", ["AlZulfi", "Shakra"])
        self.graph.add_node("AlRass", ["Al-Badai"])
        self.graph.add_node("Dhalfa", ["Sheehyah", "Mulaida"])
        self.graph.add_node("Shakra", ["UmSedrah"])
        self.graph.add_node("Mulaida", ["Dhalfa"])
        print("graph has been setup.")

    def set_starting_city(self):
        """set the starting city as a string"""
        cities = self.graph.get_all_nodes()
        print("Choose a city number to start with:" + "\n")
        self.start_city = cities[get_user_choice(cities)]
        print("you will start at", self.start_city, "city")

    def set_target_city(self):
        """set the starting city as a string"""
        cities = self.graph.get_all_nodes()
        print("Choose a city number as a target:" + "\n")
        self.target_city = cities[get_user_choice(cities)]
        print("your target city is", self.target_city, "city")

    def depth_first_search(self):
        """travel form start_city to target_city from left to right while logging the traveled cities"""
        visited_cities = []
        print("----------Depth First Search Traverse-------------")
        self.stack.unique_push(self.start_city)

        while not self.stack.is_empty():
            current_city = self.stack.pop()
            visited_cities.append(current_city)
            print("I am at", current_city, "city")
            self.stack.display()
            print("Visited cities are:", visited_cities)
            if current_city is self.target_city:
                print("I have reached the target city")
                break
            else:
                children_of_city = self.graph.get_children_of_node(
                    current_city)
                print("The children cities are:", children_of_city)
                for city in children_of_city:
                    # push to stack if not visited and not in stack
                    if city not in visited_cities:
                        self.stack.unique_push(city)
                        # print(city, "has been added to stack")

                self.stack.display()
            print("-----------------------------------------")
예제 #20
0
import http.server
import socketserver
import json
from data_structure import Stack, Linked_list

PORT = 8000

myStack = Stack()
myList = Linked_list()


def ParseRequest(self):
    if not self.headers["Content-Length"]:
        SendResponse(self, 411, "No 'Content-Length' provided")
        return
    content_length = int(self.headers["Content-Length"])
    request = json.loads(self.rfile.read(content_length).decode("UTF-8"))
    return request


def SendResponse(self, responseCode, responsebody=None):
    if responsebody:
        self.send_response(responseCode)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write(bytes(responsebody, "UTF-8"))
    else:
        self.send_response(responseCode)
        self.end_headers()
    return
예제 #21
0
 def __init__(self):
     self.stack_in = Stack()
     self.stack_out = Stack()
예제 #22
0
 def __init__(self):
     super().__init__()
     self.min_stack = Stack()