def __repr__(self):
        level = 0
        q = Queue()
        visit_order = list()
        node = self.get_root()
        q.enqueue( (node,level) )

        while q.size() > 0:
            node, level = q.dequeue()
            if node == None:
                visit_order.append( ("<empty>", level))
                continue
            visit_order.append( (node, level) )
            if node.has_left_child():
                q.enqueue( (node.get_left_child(), level +1 ))
            else:
                q.enqueue( (None, level +1) )

            if node.has_right_child():
                q.enqueue( (node.get_right_child(), level +1 ))
            else:
                q.enqueue( (None, level +1) )

        s = "Tree\n"
        previous_level = -1
        for i in range(len(visit_order)):
            node, level = visit_order[i]
            if level == previous_level:
                s += " | " + str(node)
            else:
                s += "\n" + str(node)
                previous_level = level

        return s
def test_queue_size():
    q = Queue()
    q.enqueue(1)
    q.enqueue(2)
    q.enqueue(3)

    assert q.size() == 3
示例#3
0
    def bft(self, starting_vertex_id):
        """
        Traverse and print each vertex in breadth-first order (a BFT) beginning from starting_vertex.
        """
        # Initialize empty queue and set of visited nodes:
        queue = Queue()
        visited = set()

        # Check if provided starting vertex is in our graph:
        if starting_vertex_id in self.vertices.keys():
            # If so, add starting vertex to queue:
            queue.enqueue(starting_vertex_id)
        else:
            return IndexError(
                f"Provided starting vertex {starting_vertex_id} does not exist in graph!"
            )

        # Process all vertices via BFT:
        while queue.size() > 0:
            # Get next vertex to process as first item in queue:
            current_vertex = queue.dequeue()
            # If the current vertex has not already been visited+processed, process it:
            if current_vertex not in visited:
                # Process current vertex:
                print(current_vertex)
                # Add adjacent vertices to queue for future processing:
                for adjacent_vertex in self.get_neighbors(current_vertex):
                    queue.enqueue(adjacent_vertex)
                # Mark current vertex as "visited" by adding to our set of visited vertices:
                visited.add(current_vertex)
示例#4
0
def josephusProblem(namelist, num):
    simqueue = Queue()
    for name in namelist:
        simqueue.enqueue(name)

    while simqueue.size() > 1:
        for i in range(num):
            simqueue.enqueue(simqueue.dequeue())

        simqueue.dequeue()

    return simqueue.dequeue()
示例#5
0
文件: map.py 项目: chrishuskey/Graphs
    def bfs(self, starting_room, target_room):
        """
        Return a list containing the shortest path from starting_room to destination_room, 
        after searching for and finding it with a breadth-first search (BFS) algorithm.
        """
        # Initialize empty queue and set of BFS-"visited" rooms:
        queue = Queue()
        visited_bfs = set()

        # Initialize path (we will add the rest of the path from starting room to target room below):
        path_rooms = [starting_room]
        path_directions = []

        # Check if provided starting room is in our map:
        if starting_room in self.rooms.keys():
            # If so, add starting room to queue:
            queue.enqueue((path_rooms, path_directions))
        else:
            return IndexError(
                f"Provided starting room {starting_room} does not exist in map!"
            )

        # Search all rooms via BFS, logging their paths (from starting_room --> room) as we go:
        while queue.size() > 0:
            # Get next room to process as first item in queue:
            current_path_rooms, current_path_directions = queue.dequeue()
            current_room = current_path_rooms[-1]

            # Check if it is the target --> if so, return its full path:
            if current_room == target_room:
                return current_path_directions  # Alternative: return (current_path_rooms, current_path_directions)

            # If the current room has not already been visited+processed, check and process it:
            if current_room not in visited_bfs and current_room in self.rooms:
                # If not, then get its neighbor rooms and add their paths to the queue for future processing:s
                neighbors = self.get_neighbors(current_room)
                for adjacent_room_direction in neighbors:
                    adjacent_room_path_rooms = current_path_rooms + [
                        neighbors[adjacent_room_direction]
                    ]
                    adjacent_room_path_directions = current_path_directions + [
                        adjacent_room_direction
                    ]
                    queue.enqueue((adjacent_room_path_rooms,
                                   adjacent_room_path_directions))
                # Mark current room as "visited" by adding to our set of visited rooms:
                visited_bfs.add(current_room)

        # If no path found in entire map, return None:
        return None
示例#6
0
def simulation(seconds, ppm):
    printer = Printer(ppm)
    print_queue = Queue()
    waiting_times = []

    for sec in range(seconds):
        if is_new_task():
            task = Task(sec)
            print_queue.enqueue(task)

        if not printer.busy() and not print_queue.is_empty():
            next_task = print_queue.dequeue()
            waiting_times.append(next_task.wait_time(sec))
            printer.start_next(next_task)

        printer.tick()

    average_wait = sum(waiting_times) / len(waiting_times)
    print("Average Wait %6.2f secs %3d tasks remaining." %
          (average_wait, print_queue.size()))
def simulation(num_seconds, pages_per_minute, num_students):
    lab_printer = Printer(pages_per_minute)
    print_queue = Queue()
    waiting_times = []

    for current_second in range(num_seconds):
        if new_print_task(num_students):
            task = Task(current_second)
            print_queue.enqueue(task)

        if (not lab_printer.busy()) and (not print_queue.is_empty()):
            nexttask = print_queue.dequeue()
            waiting_times.append(nexttask.wait_time(current_second))
            lab_printer.start_next(nexttask)

        lab_printer.tick()

    average_wait = sum(waiting_times) / len(waiting_times)
    print("Average Wait %6.2f secs %3d tasks remaining." %
          (average_wait, print_queue.size()))
示例#8
0
    def bfs(self, starting_vertex, target_vertex):
        """
        Return a list containing the shortest path from starting_vertex to destination_vertex, 
        after searching for and finding it with a breadth-first search (BFS) algorithm.
        """
        # Initialize empty queue and set of visited nodes:
        queue = Queue()
        visited = set()

        # Initialize path (we will add the rest of the path from starting vertex to target vertex below):
        path = [starting_vertex]

        # Check if provided starting vertex is in our graph:
        if starting_vertex in self.vertices.keys():
            # If so, add starting vertex to queue:
            queue.enqueue(path)
        else:
            return IndexError(
                f"Provided starting vertex {starting_vertex} does not exist in graph!"
            )

        # Process all vertices via BFT:
        while queue.size() > 0:
            # Get next vertex to process as first item in queue:
            current_path = queue.dequeue()
            current_vertex = current_path[-1]
            # If the current vertex has not already been visited+processed, check and process it:
            if current_vertex not in visited:
                # Check if it is the target --> if so, return its full path:
                if current_vertex == target_vertex:
                    return current_path
                # If not, then get its neighbor vertices and add their paths to the queue for future processing:
                for adjacent_vertex in self.get_neighbors(current_vertex):
                    adjacent_vertex_path = current_path + [adjacent_vertex]
                    queue.enqueue(adjacent_vertex_path)
                # Mark current vertex as "visited" by adding to our set of visited vertices:
                visited.add(current_vertex)

        # If no path found in entire graph, return None:
        return None
def simulation(numSeconds, numStudents, pagesPerMinute):

    labprinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingtimes = []

    for currentSecond in range(numSeconds):
        if newPrintTask(numStudents):
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not labprinter.busy()) and (not printQueue.isEmpty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append(nexttask.waitTime(currentSecond))
            labprinter.startNext(nexttask)

        labprinter.tick()

    averageWait = sum(waitingtimes) / len(waitingtimes)
    print("Average Wait %6.2f secs %3d tasks remaining." %
          (averageWait, printQueue.size()))
    return averageWait
示例#10
0
class TestQueue(unittest.TestCase):  # FIFO

    def setUp(self):
        self.emptyQueue = Queue()
        self.Queue = Queue()

        for i in range(5):
            self.Queue.enqueue(i)

    def test_repr(self):
        '''Test returning the queue as a string literal.'''
        self.assertEqual(repr(self.emptyQueue), str(()))
        tup = (1, 3.14, 'foo', True)

        for i in tup:
            self.emptyQueue.enqueue(i)

        self.assertEqual(repr(self.emptyQueue), str(tup))

    def test_len_size(self):
        '''Test returning the size of the queue.'''
        for i in range(100):
            self.emptyQueue.enqueue(i)

        self.assertEqual(len(self.emptyQueue), 100)
        self.assertEqual(self.emptyQueue.size(), 100)

        self.emptyQueue.dequeue()
        self.assertEqual(len(self.emptyQueue), 99)
        self.assertEqual(self.emptyQueue.size(), 99)

    def test_tuple(self):
        '''Test returning the queue as a tuple literal.'''
        self.assertEqual(tuple(self.emptyQueue), ())
        tup = (1, 3.14, 'foo', True)

        for i in tup:
            self.emptyQueue.enqueue(i)

        self.assertEqual(tuple(self.emptyQueue), tup)

    def test_list(self):
        '''Test returning the queue as a list literal.'''
        self.assertEqual(list(self.emptyQueue), [])
        li = [1, 3.14, 'foo', True]

        for i in li:
            self.emptyQueue.enqueue(i)

        self.assertEqual(list(self.emptyQueue), li)

    def test_enqueue(self):
        '''Test adding items to the front of the queue.'''
        self.Queue.enqueue(True)
        self.assertEqual(tuple(self.Queue), (0, 1, 2, 3, 4, True))

    def test_dequeue(self):
        '''Test removing items from the front of the queue.'''
        self.assertEqual(self.Queue.dequeue(), 0)
        self.assertEqual(tuple(self.Queue), (1, 2, 3, 4))
        self.assertEqual(self.Queue.dequeue(), 1)
        self.assertEqual(self.Queue.dequeue(), 2)
        self.assertEqual(self.Queue.dequeue(), 3)
        self.assertEqual(self.Queue.dequeue(), 4)
        self.assertEqual(tuple(self.Queue), ())

        with self.assertRaises(ValueError):
            self.Queue.dequeue()

        # test enqueuing after dequeuing
        self.Queue.enqueue(0)
        self.Queue.enqueue(True)
        self.assertEqual(tuple(self.Queue), (0, True))

    def test_peek(self):
        '''Test peeking at the first enqueued item w/o modifying the queue.'''
        self.assertEqual(self.Queue.peek(), 0)

        with self.assertRaises(ValueError):
            self.emptyQueue.peek()
示例#11
0
print(stack)

for i in range(5):
    stack.push(i)
    print(stack)
for i in range(stack.size()):
    stack.pop()
    print(stack)

print("*** Queue ***")
print(queue)

for i in range(5):
    queue.enqueue(i)
    print(queue)
for i in range(queue.size()):
    queue.dequeue()
    print(queue)

print("*** Deque - Stack operation ***")
print(deque)

for i in range(5):
    deque.add_rear(i)
    print(deque)
for i in range(deque.size()):
    deque.remove_rear()
    print(deque)

print("*** Deque - Queue operation ***")
print(deque)