Exemple #1
0
def remove_batch(queue, year):
    """
    -------------------------------------------------------
    Description:
        Remove students enrolled in given year from a given queue
        Function process queue items sequentially:
        if year does not match, item is moved to rear of queue
        students removed are stored in a queue
    Use: batch_queue = remove_batch(queue,year)
    -------------------------------------------------------
    Parameters:
        queue - a queue object containing student objects (Queue)
        year - enrollment year (int)
    Returns:
        batch_queue - a queue containing students of same batch          
    -------------------------------------------------------
    """
    batch_queue = Queue()
    if isinstance(year, int):
        for _ in range(len(queue)):
            student = deepcopy(queue.remove())
            student_key = student.key()

            if str(year) in student_key:
                batch_queue.insert(student)
            else:
                queue.insert(student)
    else:
        print('Error(remove_batch): invalid input parameter type')
    return batch_queue
def test_enqueue():
    queue = Queue()

    queue.enqueue(1)
    queue.enqueue(2)

    assert queue.head.value == 2
    assert queue.tail.value == 1
Exemple #3
0
def hot_potato(name_list, num):
    simqueue = Queue()
    for name in name_list:
        simqueue.enqueue(name)
    while simqueue.size > 1:
        for _ in range(num - 1):
            simqueue.enqueue(simqueue.dequeue())
        simqueue.dequeue()
    return simqueue.dequeue()
Exemple #4
0
 def pop(self, pop_type=None):
     new_stack = Queue()
     while self.__stack.size() > 0:
         current_value = self.__stack.pop()
         if self.__stack.size() == 0:
             if pop_type is not None:
                 new_stack.push(current_value)
             self.__stack = new_stack
             return current_value
         new_stack.push(current_value)
def test_get_size():
    queue = Queue()
    assert queue.get_size() == 0
    queue.enqueue(1)
    assert queue.get_size() == 1
    queue.dequeue()
    assert queue.get_size() == 0
Exemple #6
0
def queue_reverser(queue):
    new_queue = Queue()
    stack = Stack()
    length = queue.length
    for _ in range(length):
        item = queue.dequeue()
        stack.push(item)
        queue.enqueue(item)
    for _ in range(length):
        new_queue.enqueue(stack.pop())
    return new_queue
def test_dequeue():
    queue = Queue()
    queue.enqueue(1)
    queue.enqueue(2)
    queue.enqueue(3)

    assert queue.dequeue() == 1
    assert queue.head.value == 3
    assert queue.tail.value == 2
    queue.dequeue()
    assert queue.dequeue() == 3
    assert queue.head is None
    assert queue.tail is None
def transform_bfs(start, target, h, t, flag):
    q = Queue()
    q.push(Word(start, True))
    counter = 0

    while not q.is_empty() and counter <= t:
        word = q.pop()
        options = generate_options(word.str)
        for opt in options:
            if opt in h:
                for candidate in h[opt]:
                    if candidate.visited != flag:
                        if candidate.visited == False:
                            if compare(candidate.str, target) == 1:
                                return word.ancestry + [
                                    word.str, candidate.str, target
                                ]
                            else:
                                candidate.visited = flag
                                candidate.ancestry = word.ancestry + [word.str]
                                q.push(candidate)
                                counter += 1
                        else:
                            return word.ancestry + [
                                word.str, candidate.str
                            ] + candidate.ancestry[::-1]
    return None
Exemple #9
0
 def __init__(self, height=30, length=30):
     self.height = height
     self.length = length
     self.grid = []
     self.grew = False
     self.head = Snake_Node(0, 0)
     # Re-used snake node to keep location of food on grid
     self.food_location = Snake_Node(0, 0)
     # The tail is a queue of snake nodes
     self.tail = Queue()
     self.isdead = False
     self.create_grid()
     self.snake_head_start_location()
     self.spawn_food()
Exemple #10
0
 def levelorder(self):
     items = []
     queue = Queue()
     node = self._root  # starting from the root
     queue.insert(node)  # insert it
     while not queue.is_empty():
         node = queue.remove()  # pick that node
         items.append(node._data)  # add to the list
         # if the left side is not None, there exist a left side, add the queue (going left to right_
         if node._left is not None:
             queue.insert(node._left)
         # you also want to add the right side
         if node._right is not None:
             queue.insert(node._right)
     return items
def test_has_limit():
    queue = Queue(1)
    assert queue.has_space() is True
    assert queue.limit == 1

    queue.enqueue(1)
    assert queue.has_space() is False
    with pytest.raises(QueueIsFull):
        queue.enqueue(2)
Exemple #12
0
 def trasverse_levelorder(self):
     levels = [[]]
     q = Queue()
     q.enqueue({"node": self.root, "level": 0})
     while not q.queue_empty():
         x = q.dequeue()
         # Save node to appropriate level.
         if x["level"] == len(levels):  # Create new level.
             levels.append([x["node"].key])
         else:  # Save to existing level.
             levels[x["level"]].append(x["node"].key)
         # Proceed with the queue.
         if x["node"].left is not None:
             q.enqueue({"node": x["node"].left, "level": x["level"] + 1})
         if x["node"].right is not None:
             q.enqueue({"node": x["node"].right, "level": x["level"] + 1})
     return levels
Exemple #13
0
 def pre_order_traversal(self) -> Queue:
     """
     This method performs a recursive pre-order traversal of the tree,
     and returns a my_queue object that contains values of visited nodes,
     in the order they were visited.
     """
     q = Queue()
     self.pre_order_traversal_helper(q, self.root)
     return q
Exemple #14
0
def bfs(land, r, c, rows, cols):
    q = Queue()
    land[r][c] = False
    q.push((r, c))
    while not q.is_empty():
        x, y = q.pop()
        for i, j in [(x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)]:
            if i in range(rows) and j in range(cols) and land[i][j]:
                land[i][j] = False
                q.push((i, j))
    return
Exemple #15
0
    def __str__(self):
        """
        -------------------------------------------------------
        Description:
            Returns a string representation of bst
            Uses Breadth First Search (BFS)
        Assert: none
        Use: str(bst) or print(bst)
        -------------------------------------------------------
        Parameters:
            None
        Returns:
            output: string representation of bst (str)
        -------------------------------------------------------
        """
        q = Queue(self.MAX_SIZE)
        output = ''

        q.insert(self._root)
        level = 1

        while not q.is_empty():
            node = q.remove()

            if node is None:
                continue

            node_level = self.level(node._data)

            if node_level == level:
                output += '{} '.format(str(node._data))

            elif node_level > level:
                output = '{}\n'.format(output[:-1])
                output += '{} '.format(str(node._data))
                level += 1

            if node._left is not None:
                q.insert(node._left)

            if node._right is not None:
                q.insert(node._right)

        return output[:-1]
Exemple #16
0
def shred_queue(queue, size):
    """
    -------------------------------------------------------
    Description:
        shreds a queue into several equal sized queues of given size.
        Items of the queue is distributed sequentially into the minoir queues.
        If given size is invalid, print error message and return empty list
        At the end of the shredding process the input queue should be restored.  
    Use: queue_list = shred_queue(queue,size)
    -------------------------------------------------------
    Parameters:
        queue - a queue containing arbitrary items (Queue)
        size - size of each mini queue (int)
    Returns:
        queues - a list containing mini queues (list)            
    -------------------------------------------------------
    """
    queues = []
    q = deepcopy(queue)

    if isinstance(size, int) and size > 0 and size < len(q) + 1:
        i = 0
        if len(queue) % size == 0:
            num_queues = len(queue) // size
        else:
            num_queues = len(queue) // size + 1

        while i < num_queues:
            new_queue = Queue(size)

            for _ in range(size):
                if q.is_empty():
                    break
                else:
                    new_queue.insert(q.remove())

            queues.append(new_queue)
            i += 1
    else:
        print("Error(shred_queue): invalid shred size")

    return queues
Exemple #17
0
 def by_level_traversal(self) -> Queue:
     """
     This method performs by-level traversal of the tree,
     and returns a my_queue object that contains values of visited nodes,
     in the order they were visited.
     """
     height = self.height()
     queue = Queue()
     for i in range(height + 1):
         self.by_level_traversal_helper(queue, self.root, i)
     return queue
Exemple #18
0
    def _reflect_vertical_aux(self, node):
        queue = Queue()
        tree = BST()

        if node is None:
            return tree

        if node is not None:
            queue.insert(node)
        while not queue.is_empty():
            temp = node._left
            node._left = node._right
            node._right = temp
            node = queue.remove()
            tree.insert(node._data)
            if node._left is not None:
                queue.insert(node._left)
            if node._right is not None:
                queue.insert(node._right)

        return tree
 def print_animation(self, names: list, num: int):
     circle_q = Queue()
     for name in names:
         circle_q.put(name)
     while True:
         # Stop the process when only one name remains
         if circle_q.size() == 1:
             break
         # When passing a potato, the simulation will simply dequeue and then immediately
         # enqueue the child, putting her at the end of the line
         for i in range(num):
             front_child = circle_q.get()
             circle_q.put(front_child)
             print("Time:", i)
             print(self.circle_q_to_str(names, front_child))
             time.sleep(1)
         # After passing potatoes `num` times, the child at the front will be removed permanently
         name = circle_q.get()
         names.remove(name)
         print('\n')
     print("The last man:", circle_q.get())
Exemple #20
0
def main():

    count = 0
    maxFrames = 72
    color_buffer = Queue()  # Buffer for color frames
    greyscale_buffer = Queue()  # Buffer for grey frames
    video_capture = cv2.VideoCapture("clip.mp4")  # Create VideoCapture obj

    threads = [  # configure threads to run specific functions
        Thread(
            target=extract_frames,
            args=[video_capture, maxFrames, color_buffer],
        ),  # Func spec Threads
        Thread(target=convert_frames, args=[color_buffer, greyscale_buffer]),
        Thread(target=render, args=[greyscale_buffer]),
    ]

    for t in threads:  # For each thread
        t.start()  # start thread
    for t in threads:  # For each thread
        t.join()  # join the threads (wait on all threads)
Exemple #21
0
 def test_get(self):
     q = Queue()
     q.put(1)
     i = q.get()
     self.assertEqual(1, i)
     with self.assertRaises(IndexError):
         i = q.get()
Exemple #22
0
 def __str__(self):
     """
     -------------------------------------------------------
     Description:
         Returns a string representation of bst
         Uses Breadth First Search (BFS)
     Assert: none
     Use: str(bst) or print(bst)
     -------------------------------------------------------
     Parameters:
         None
     Returns:
         output: string representation of bst (str)
     -------------------------------------------------------
     """
     # You can all the way down print the depth (DFS depth first search) --> Stacks
     # Horizontal search, reads horizontally to prints (BFS breath first search) --> Queues
     q = Queue(self.MAX_SIZE)
     output = ''
     q.insert(self._root)
     level = 1
     # come back to this in WEEK #11
     while not q.is_empty():
         node = q.remove()
         if node is None:
             continue
         node_level = self.level(node._data)
         if node_level == level:
             output += str(node._data) + ' '
         elif node_level > level:
             output = output[:-1] + '\n'
             output += str(node._data) + ' '
             level += 1
         if node._left is not None:
             q.insert(node._left)
         if node._right is not None:
             q.insert(node._right)
     return output[:-1]
Exemple #23
0
def bfs(start: Vertex):
    """Breadth first search which does not effect the edges of the graph"""
    v_queue = Queue()
    v_queue.put(start)
    while not v_queue.empty():
        curr_v = v_queue.get()
        for nbr in curr_v.get_out_neighbors():
            if not nbr.color:
                nbr.color = 'g'
                nbr.add_in_neighbor(curr_v)
                v_queue.put(nbr)
            else:
                pass
                # TODO: delete out_neighbor of curr_v
                # TODO: delete in_neighbor of nbr
        curr_v.color = 'b'
Exemple #24
0
class AnimalShelter:
    def __init__(self):
        self.dogs = Queue()
        self.cats = Queue()
        self.counter = 0

    def enqueue(self, *, name, species):
        if species in Animal.VALID_SPECIES:
            self.counter += 1
            getattr(self, f"{species}s").push(
                Animal(name=name, species=species, counter=self.counter))
        else:
            raise AttributeError("INVALID TYPE")

    def dequeue_cat(self):
        if self.cats.is_empty():
            raise IndexError("EMPTY CAT QUEUE")
        else:
            return self.cats.pop().name

    def dequeue_dog(self):
        if self.dogs.is_empty():
            raise IndexError("EMPTY DOG QUEUE")
        else:
            return self.dogs.pop().name

    def dequeue_any(self):
        if self.dogs.is_empty() and self.cats.is_empty():
            raise IndexError("EMPTY QUEUE")
        elif self.dogs.is_empty():
            return self.dequeue_cat()
        elif self.cats.is_empty():
            return self.dequeue_dog()
        else:
            return self.dequeue_cat() if self.dogs.peek(
            ).counter > self.cats.peek().counter else self.dequeue_dog()
def breadth_first_search_adjlist(graph, source, destination):
    if not source in graph.vertices:
        print('Source does not exist in graph')
        return
    if not destination in graph.vertices:
        print('destination does not exist in graph')
        return

    #Set inital parameters for source vert, enqueue source
    graph.vertex_object[source].color = 'grey'
    graph.vertex_object[source].distance = 0
    graph.vertex_object[source].prev_search = None

    bfs_queue = Queue()
    bfs_queue.enqueue(source)

    #BFS while loop. Search closest nodes and set distances from source/build tree
    while not bfs_queue.is_empty():
        current_vert = graph.vertex_object[bfs_queue.dequeue()]
        print(current_vert.name)
        for vertex in graph.vertices[current_vert.name]:
            if graph.vertex_object[vertex].color == 'white':
                graph.vertex_object[vertex].color = 'grey'
                graph.vertex_object[
                    vertex].distance = current_vert.distance + 1
                graph.vertex_object[vertex].prev_search = current_vert.name
                bfs_queue.enqueue(vertex)

                print('Vertex:' + vertex)

    vertex_iterator = graph.vertex_object[destination]
    bfs_stack = []

    while vertex_iterator != graph.vertex_object[source]:
        if not vertex_iterator.prev_search:
            print('No path between source and destination')
            return

        bfs_stack.append(vertex_iterator.name)
        vertex_iterator = graph.vertex_object[vertex_iterator.prev_search]

    bfs_stack.append(source)

    print([x for x in reversed(bfs_stack)])
Exemple #26
0
    def bfs(gui, one_step=False):
        starting_pos = gui.grid.head.get_node()
        fringe = Queue()
        # Fringe holds a list of tuples: (node position, move to get prev to current, cost)
        fringe.enqueue([(starting_pos, None, 0)])
        path = []
        visited = [starting_pos]
        while not fringe.is_empty():
            # Get the next one to be popped off the stack to search it's neighbor nodes (successors)
            path = fringe.dequeue()

            if gui.grid.grid[path[-1][0][0]][path[-1][0][1]] == 3:
                break

            for neighbor in get_neighbors(gui, path[-1][0][0], path[-1][0][1]):
                if neighbor[0] not in visited:
                    updated_path = copy.copy(path)
                    updated_path.append(neighbor)
                    fringe.enqueue(updated_path)
                    if not gui.grid.grid[neighbor[0][0]][neighbor[0][1]] == 3:
                        visited.append(neighbor[0])

        if not fringe.is_empty():
            move_set = []
            while path:
                temp = path.pop(0)
                if temp[1] is not None:
                    move_set.append(temp[1])
            if not one_step:
                return move_set
            else:
                return [move_set[0]]
        else:
            no_bfs_move = go_furthest(gui)
            if no_bfs_move:
                return no_bfs_move
            else:
                no_moves_at_all = go_down()
                return no_moves_at_all
Exemple #27
0
    def find_nearest_shop(self):
        visited = []
        queue = Queue()
        queue.push(self.__start_index)

        while queue.size() != 0:
            current = queue.pop()
            if current is not None:
                if self.__shop_lists[current] != 0:
                    return current
                for e in range(len(self.__map[current])):
                    if self.__map[current][e] != 0 and e not in visited:
                        queue.push(e)
            visited.append(current)
        return None
def paint_fill_bfs(screen, x, y, new):
    old = screen[x][y]
    if old == new:
        return
    q = Queue()
    q.push((x, y))
    screen[x][y] = new

    while q.length > 0:
        r, c = q.pop()
        surrounding = [(r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)]
        for t, s in surrounding:
            if (t in range(len(screen)) and s in range(len(screen[0]))
                    and screen[t][s] == old):
                screen[t][s] = new
                q.push((t, s))
    return
def simulate(num_seconds, pages_per_minute):
    printer = Printer(pages_per_minute)
    print_queue = Queue()
    waiting_times = []

    for curr_sec in range(num_seconds):
        if is_create_new_print_task():
            task = RandomTask(curr_sec)
            print_queue.put(task)

        if (not printer.is_busy()) and (not print_queue.empty()):
            next_task = print_queue.get()
            waiting_times.append(next_task.get_wait_time(curr_sec))
            printer.start_next(next_task)
        printer.tick()
    avg_wait_time = sum(waiting_times) / len(waiting_times)
    return avg_wait_time, print_queue.size()
def simulation(numSeconds, pagesPerMinute):
    labprinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingtimes = []

    for currentSecond in range(numSeconds):

        if newPrintTask():
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not labprinter.busy()) and (not printQueue.empty()):
            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()))
Exemple #31
0
class Stack:

    def __init__(self):
        self.__stack = Queue()

    # Adds value to the end of the Stack.
    # Complexity: O(1)
    # push(value)
    def push(self, value):
        self.__stack.push(value)

    # Returns value from the end of the Stack and removes it.
    # Complexity: O(1)
    # pop()
    def pop(self, pop_type=None):
        new_stack = Queue()
        while self.__stack.size() > 0:
            current_value = self.__stack.pop()
            if self.__stack.size() == 0:
                if pop_type is not None:
                    new_stack.push(current_value)
                self.__stack = new_stack
                return current_value
            new_stack.push(current_value)

    # Returns value from the end of the Stack without removing it.
    # Complexity: O(1)
    def peek(self):
        return self.pop(1)

    # Returns the number of elements in the Queue.
    # Complexity: O(1)
    def size(self):
        return self.__stack.size()

    def getStack(self):
        return self.__stack.getQueue()
Exemple #32
0
def reverse_stack(stack):
    """
    -------------------------------------------------------
    Description:
        Reverse a stack using a queue
    Use: reverse_stack(stack)
    -------------------------------------------------------
    Parameters:
        stack - a stack of items (Stack)
    Returns:
        No returns
    -------------------------------------------------------
    """
    queue = Queue()
    
    while not stack.is_empty():
        item = deepcopy(stack.pop())
        queue.insert(item)
    
    while not queue.is_empty():
        stack.push(queue.remove())

    return
Exemple #33
0
print("container of size: " + str(lis.get_size()) + ":")
print(lis)
print(lis.pop_front())
print(lis.pop_front())
print(lis.pop_front())
print(lis.pop_front())
print("container of size: " + str(lis.get_size()) + ":")
print(lis)
print(lis.pop_front())
print(lis.pop_front())
print("container of size: " + str(lis.get_size()) + ":")
print(lis)

print("\nTESTING QUEUE WITH ARRAYS\n")

queue = Queue("array")
queue.add(2)
queue.add(4)
queue.add(7)
print("the data structure is of size: " + str(queue.get_size()))
print(queue.remove())
print(queue.remove())
print(queue.remove())
print(queue.remove())
print("the data structure is of size: " + str(queue.get_size()))

print("\nTESTING STACK WITH ARRAYS\n")

stack = Stack("array")
stack.push(2)
stack.push(4)
Exemple #34
0
 def __init__(self):
     self.__stack = Queue()
Exemple #35
0
    print(stack.pop())

    '''------------Second Part--------------'''
    # user enters str values into stack
    line = input("Enter a string,'end' to stop: ")
    while (line != 'end'):
        stack.push(line)
        line = input("Enter a string,'end' to stop:")

    # user typed str values are removed from stack and printed
    while not(stack.is_empty()):
        print(stack.pop())

    '''-------------Third Part----------------'''
    # same user interaction as before, except use a Queue instead of Stack
    queue = Queue()
    line = int(input("Enter a string,'end' to stop: "))
    while (line != 'end'):
        queue.enqueue(line)

        #convert line to an int unless it is 'end'
        line = (input("Enter a string,'end' to stop:"))
        if  line != 'end':
        	line = int(line)

    product = 1
    while not(queue.is_empty()):
        product *= queue.dequeue()

    print(product)