Exemple #1
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()
    def test_queue_size_after_dequeue_on_complete_queue(self):
        queue = Queue()

        items = [3, 4, 1, 111, "abcd", "item 5"]

        for item in items:
            queue.enqueue(item)

        # Dequeue operation on complete queue
        for i in range(len(items)):
            queue.dequeue()

        self.assertEqual(queue.length, QUEUE_LENGTH_ZERO)
    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_dequeue(self):
        q = Queue(1)
        q.enqueue(2)
        q.enqueue(3)
        q.enqueue(4)

        self.assertEqual(len(q), 4)
        self.assertEqual(q.peek(), 1)
        q.dequeue()
        self.assertEqual(len(q), 3)
        self.assertEqual(q.peek(), 2)

        while q.storage:
            q.dequeue()

        self.assertRaises(IndexError, q.dequeue)
    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)
Exemple #6
0
    def BFS(self, src):
        """ Performs Breadth First Search on self.graph from :src: node """
        # Initialization
        visited = [False
                   ] * self.v  # Whether the node i has been visited or not
        d = [math.inf] * self.v  # d[i] is distance from src to node i
        p = [None] * self.v  # p[i] is parent of node i in the traversal
        traversal_order = []  # Final traversal order
        q = Queue(self.v)

        visited[src] = True
        d[src] = 0
        q.enqueue(src)

        while not q.is_empty():
            u = q.dequeue()
            traversal_order.append(u)
            adj = self.graph[u].head
            while adj != None:  # Adj vertices
                v = adj.val[0]  # Vertex
                if not visited[v]:
                    visited[v] = True
                    d[v] = d[u] + 1
                    p[v] = u
                    q.enqueue(v)
                adj = adj.next
        return traversal_order, d, p
def test_dequeue_item():
    q = Queue()
    q.enqueue(1)
    q.enqueue(2)
    item = q.dequeue()

    assert item == 1
Exemple #8
0
    def _BFS(self, source=None, sink=None, nodes=None):
        """Breadth first search (BFS).
        Finds a path between source and sink and returns it. If no path is found returns false"""

        if source is None:
            source = self.source
        if sink is None:
            sink = self.sink
        if nodes is None:
            nodes = self.nodes

        for node in nodes:
            node.visited = False

        q = Queue()
        q.enqueue(source)
        source.visited = True
        while not q.is_empty():
            current_node = q.dequeue()
            children = current_node.children
            for i in range(len(children)):
                child = children[i]
                if current_node.name.lower() == "source":
                    residual_capacity = current_node.residual_capacity[i]
                else:
                    residual_capacity = child.residual_capacity
                if child.name == sink.name:
                    return self._extract_path_from_bfs(current_node, source,
                                                       sink)
                if not child.visited and residual_capacity > 0:
                    child.visited = True
                    child.parent = current_node
                    q.enqueue(child)

        return False  # no path found
Exemple #9
0
def interleave_stack(stack):
    '''
This problem was asked by Google.

Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue. This should be done in-place.

Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue.

For example, if the stack is [1, 2, 3, 4, 5], it should become [1, 5, 2, 4, 3]. If the stack is [1, 2, 3, 4], it should become [1, 4, 2, 3].
    '''

    stack_size = 0
    queue = Queue()
    while True:
        try:
            queue.enqueue(stack.pop())
            stack_size += 1
        except IndexError:
            break

    while True:
        try:
            stack.push(queue.dequeue())
        except IndexError:
            break

    while True:
        try:
            queue.enqueue(stack.pop())
        except IndexError:
            break

    while True:
        try:
            stack.push(queue.dequeue())
        except IndexError:
            break

    for regurgitation_size in range(stack_size - 1, 0, -1):
        for _ in range(regurgitation_size):
            queue.enqueue(stack.pop())
        for _ in range(regurgitation_size):
            stack.push(queue.dequeue())

    return stack
    def test_dequeue_on_first_item_enqueue(self):
        queue = Queue()

        item = 5

        queue.enqueue(item)

        dequeue_item = queue.dequeue()

        self.assertEqual(dequeue_item, item)
    def test_dequeue_on_subsequent_item_enqueue(self):
        queue = Queue()

        items = [3, 4, 1, 111, "abcd", "item 5"]

        for item in items:
            queue.enqueue(item)

        # Dequeue operation on complete queue
        for i in range(len(items)):
            self.assertEqual(queue.dequeue(), items[i])
Exemple #12
0
    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
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()))
Exemple #14
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 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
Exemple #17
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()
    def test_exception_on_dequeue_on_empty_queue(self):
        queue = Queue()

        with self.assertRaises(exceptions.EmptyQueueException):
            queue.dequeue()
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)
def single_bfs(big_list, current):
    queue = Queue()
    explored = Queue()
    newExplored = Stack()
    seen = set()

    pointer = current

    queue.enqueue(pointer)  #Add the our initial position to the
    explored.enqueue(pointer)  #queue
    tra_model = Tra_model()

    while True:

        if queue.isEmpty():
            break
        else:
            pointer = queue.dequeue()
            # First move to the right and check what it is
            pointer = tra_model.move_right(pointer)  #make the first move
            x = pointer[0]
            y = pointer[1]

            if big_list[x][y] == " ":  #if it is space, add its location
                queue.enqueue(pointer)
                explored.enqueue(pointer)
                big_list[x][y] = "#"
                pointer = tra_model.move_left(pointer)
            if big_list[x][y] == "%" or "#":  #if it is hardle, move back
                pointer = tra_model.move_left(pointer)

            if big_list[x][y] == ".":  #if it is goal, add its location
                queue.enqueue(pointer)
                explored.enqueue(pointer)
                break

    # second move to the bottom and check what it is

            pointer = tra_model.move_down(pointer)

            x = pointer[0]
            y = pointer[1]

            if big_list[x][y] == " ":  #if it is space, add its location
                explored.enqueue(pointer)
                queue.enqueue(pointer)
                big_list[x][y] = "#"
                pointer = tra_model.move_up(pointer)
            if big_list[x][y] == "%" or "#":  #if it is hardle, move back
                pointer = tra_model.move_up(pointer)
            if big_list[x][y] == ".":  #if it is goal, add its location
                queue.enqueue(pointer)
                explored.enqueue(pointer)
                break

    # Third move to the left and check what it is

            pointer = tra_model.move_left(pointer)
            x = pointer[0]
            y = pointer[1]

            if big_list[x][y] == " ":  #if it is space, add its location
                explored.enqueue(pointer)
                queue.enqueue(pointer)
                big_list[x][y] = "#"
                pointer = tra_model.move_right(pointer)
            if big_list[x][y] == "%" or "#":  #if it is hardle, move back
                pointer = tra_model.move_right(pointer)
            if big_list[x][y] == ".":  #if it is goal, add its location
                queue.enqueue(pointer)
                explored.enqueue(pointer)
                break

    # Fourth move to the left and check what it is

            pointer = tra_model.move_up(pointer)
            x = pointer[0]
            y = pointer[1]

            if big_list[x][y] == " ":  #if it is space, add its location
                explored.enqueue(pointer)
                queue.enqueue(pointer)
                big_list[x][y] = "#"
                pointer = tra_model.move_down(pointer)
            if big_list[x][y] == "%" or "#":  #if it is hardle, move back
                pointer = tra_model.move_down(pointer)
            if big_list[x][y] == ".":  #if it is goal, add its location
                queue.enqueue(pointer)
                explored.enqueue(pointer)
                break

    expanded = 0
    for i in explored.items:
        expanded += 1

    steps = 0
    for item in explored.items:
        t = tuple(item)
        if t not in seen:
            steps += 1
            newExplored.push(item)
            seen.add(t)

    return newExplored, big_list, steps, expanded