Beispiel #1
0
def test_remove_all_but_one_doctest2() -> None:
    """Test is the doctest given in remove_all_but_one."""
    queue = Queue()
    queue.enqueue(2)
    queue.enqueue(2)
    queue.enqueue(3)
    remove_all_but_one(queue)
    assert queue.is_empty() is False
    assert queue.dequeue() == 3
    assert queue.is_empty()
Beispiel #2
0
def list_nestedness(lst: List[int], q: Queue) -> List[List[int]]:
    """
    Return a list of elements of lst in each level of nestedness using q.

    Precondition: q is empty.
                  lst contains only ints.

    >>> lst = [1, [[[2], 3]], [4, [5]]]
    >>> list_nestedness(lst, Queue())
    [[1], [4], [3, 5], [2]]
    """
    # Step 1. Add all of the items from lst into c
    for item in lst:
        q.add(item)

    # LIST_NESTEDNESS - 2. Add "END" to the Queue
    q.add("END")

    # LIST_NESTEDNESS - 3. Create an empty list called level
    level = []

    # LIST_NESTEDNESS - 4. Create an empty list called all_levels
    all_levels = []

    # Step 2. Repeat the following until c is empty
    while not q.is_empty():
        # Step 2a. Remove an item from the container
        removed_item = q.remove()

        # Step 2b. If that item is not a list, print it out
        if not isinstance(removed_item, list):
            # LIST_NESTEDNESS - 5B. If removed_item is "END" append level to
            # all_levels and set level to an empty list.
            if removed_item == "END":
                all_levels.append(level)
                level = []

                # LIST_NESTEDNESS - 5BI. If the Queue is not empty, add "END"
                # to the Queue
                if not q.is_empty():
                    q.add("END")
            else:
                # LIST_NESTEDNESS - 5C. If removed_item is not a list or "END",
                # add it to the list 'level'
                level.append(removed_item)
        else:
            # Step 2c. If it is a list, add all of its items into c
            for item in removed_item:
                q.add(item)

    # Return all_levels when we're done.
    return all_levels
def simulate_one_server(input_file):
    """
    Server simulator
    :param input_file: (File) - Request inputs file.
    :return: (Float) - Average wait time for a request
    """
    www = Server()
    req_queue = Queue()
    try:
        with open(input_file, 'rb') as infile:
            req_data = csv.reader(infile)
            w_times = []
            for row in req_data:
                req_queue.enqueue(Request(row))
                if not www.busy() and not req_queue.is_empty():
                    curr = req_queue.dequeue()
                    www.start_next(curr)
                    curr_time = curr.get_stamp()
                    w_times.append(curr.wait_time(curr_time))
                    www.tick()
            avg_wait = float(sum(w_times)) / len(w_times)
            return 'Average wait: {:.2f} seconds\n' \
                   '\t Tasks remaining {}' \
                .format(avg_wait, req_queue.size())
    except IOError:
        print 'Could not open {}'.format(input_file)
Beispiel #4
0
def test_remove_all_doctest() -> None:
    """This is the doctest given in remove_all."""
    queue = Queue()
    queue.enqueue(1)
    queue.enqueue(2)
    queue.enqueue(3)
    remove_all(queue)
    assert queue.is_empty()
Beispiel #5
0
def filter_queue(q: Queue, min: int) -> None:
    """Remove all items from <q> that are less than <minimum>.
        >>> q = Queue()
        >>> q.enqueue(2)
        >>> q.enqueue(21)
        >>> q.enqueue(5)
        >>> q.enqueue(1)
        >>> filter_queue(q, 10)
        >>> q.dequeue()
        21
        >>> q.is_empty()
        True
        """
    temp_queue = Queue()
    while not q.is_empty():
        value = q.dequeue()
        if value >= min:
            temp_queue.enqueue(value)
    while not temp_queue.is_empty():
        q.enqueue(temp_queue.dequeue())
Beispiel #6
0
def remove_all(queue: Queue) -> None:
    """Remove all items from the given queue.

    >>> queue = Queue()
    >>> queue.enqueue(1)
    >>> queue.enqueue(2)
    >>> queue.enqueue(3)
    >>> remove_all(queue)
    >>> queue.is_empty()
    True
    """
    while not queue.is_empty():
        queue.dequeue()
Beispiel #7
0
def remove_all_but_one(queue: Queue) -> None:
    """Remove all items from the given queue except the last one
    (the one just added).

    Precondition: <queue> contains at least one item.
                  or: not queue.is_empty()

    >>> queue = Queue()
    >>> queue.enqueue(1)
    >>> queue.enqueue(2)
    >>> queue.enqueue(3)
    >>> remove_all_but_one(queue)
    >>> queue.is_empty()
    False
    >>> queue.dequeue()
    3
    >>> queue.is_empty()
    True
    """
    while not queue.is_empty():
        a = queue.dequeue()
        if queue.is_empty():
            queue.enqueue(a)
            return
Beispiel #8
0
    def solve(self,
              puzzle: Puzzle,
              seen: Optional[Set[str]] = None) -> List[Puzzle]:
        """
        Return a list of puzzle states representing a path to a solution of
        <puzzle>. The first element in the list should be <puzzle>, the
        second element should be a puzzle that is in <puzzle>.extensions(),
        and so on. The last puzzle in the list should be such that it is in a
        solved state.

        In other words, each subsequent item of the returned list should take
        the puzzle one step closer to a solution, which is represented by the
        last item in the list.

        Return an empty list if the puzzle has no solution.

        <seen> is either None (default) or a set of puzzle states' string
        representations, whose puzzle states can't be any part of the path to
        the solution.
        """

        if puzzle.is_solved():
            return [puzzle]

        puzzle_copy = puzzle.extensions()
        path_options = Queue()
        path_options.enqueue(puzzle_copy)
        path = []
        seen = []

        while not path_options.is_empty():
            path.extend(path_options.dequeue())
            puzzle_copy = []
            for states in path:
                if any(str(states) in fails for fails in seen):
                    path.remove(states)
                elif states.fail_fast():
                    seen.append(str(path.remove(states)))
                else:
                    puzzle_copy.extend(states.extensions())
            if not puzzle_copy:
                path_options = Queue()
            if path[-1].is_solved:
                return path
            else:
                path_options.enqueue(puzzle_copy)
Beispiel #9
0
    def solve(self, puzzle: Puzzle,
              seen: Optional[Set[str]] = None) -> List[Puzzle]:
        """
        Return a list of puzzle states representing a path to a solution of
        <puzzle>. The first element in the list should be <puzzle>, the
        second element should be a puzzle that is in <puzzle>.extensions(),
        and so on. The last puzzle in the list should be such that it is in a
        solved state.

        In other words, each subsequent item of the returned list should take
        the puzzle one step closer to a solution, which is represented by the
        last item in the list.

        Return an empty list if the puzzle has no solution.

        <seen> is either None (default) or a set of puzzle states' string
        representations, whose puzzle states can't be any part of the path to
        the solution.
        """
        if puzzle.fail_fast():
            return []
        if seen is not None:
            if str(puzzle) in seen:
                return []
        if puzzle.is_solved():
            return [puzzle]
        if seen is None:
            seen = {str(puzzle)}
        else:
            seen.add(str(puzzle))
        queue = Queue()
        for extension in puzzle.extensions():
            queue.enqueue([puzzle, extension])
        while not queue.is_empty():
            curr_path = queue.dequeue()
            examine = curr_path[-1]
            if examine.is_solved():
                if seen is None or str(examine) not in seen:
                    return curr_path
            if not (examine.fail_fast() or (str(examine) in seen)):
                seen.add(str(examine))
                for extension in examine.extensions():
                    new_path = curr_path + [extension]
                    queue.enqueue(new_path)
        return []
Beispiel #10
0
    def solve(self, puzzle: Puzzle,
              seen: Optional[Set[str]] = None) -> List[Puzzle]:
        """
        Return a list of puzzle states representing a path to a solution of
        <puzzle>. The first element in the list should be <puzzle>, the
        second element should be a puzzle that is in <puzzle>.extensions(),
        and so on. The last puzzle in the list should be such that it is in a
        solved state.

        In other words, each subsequent item of the returned list should take
        the puzzle one step closer to a solution, which is represented by the
        last item in the list.

        Return an empty list if the puzzle has no solution.

        <seen> is either None (default) or a set of puzzle states' string
        representations, whose puzzle states can't be any part of the path to
        the solution.
        """

        queue = Queue()

        if seen is None:
            seen = set()

        queue.enqueue([puzzle])

        while not queue.is_empty():
            lst = queue.dequeue()
            p = lst[-1]
            if p.fail_fast() or str(p) in seen:
                if str(p) not in seen:
                    seen.add(str(p))
            elif p.is_solved():
                return lst
            else:
                for puz in p.extensions():
                    sublst = lst + [puz]
                    queue.enqueue(sublst)
        return []
Beispiel #11
0
def remove_all_but_one(queue: Queue) -> None:
    """Remove all items from the given queue except the last one.

    Precondition: <queue> contains at least one item.
                  or: not queue.is_empty()

    >>> queue = Queue()
    >>> queue.enqueue(1)
    >>> queue.enqueue(2)
    >>> queue.enqueue(3)
    >>> remove_all_but_one(queue)
    >>> queue.is_empty()
    False
    >>> queue.dequeue()
    3
    >>> queue.is_empty()
    True
    """
    item = 0
    while not queue.is_empty():
        item = queue.dequeue()
    queue.enqueue(item)
Beispiel #12
0
    def solve(self,
              puzzle: Puzzle,
              seen: Optional[Set[str]] = None) -> List[Puzzle]:
        """
        Return a list of puzzle states representing a path to a solution of
        <puzzle>. The first element in the list should be <puzzle>, the
        second element should be a puzzle that is in <puzzle>.extensions(),
        and so on. The last puzzle in the list should be such that it is in a
        solved state.

        In other words, each subsequent item of the returned list should take
        the puzzle one step closer to a solution, which is represented by the
        last item in the list.

        Return an empty list if the puzzle has no solution.

        <seen> is either None (default) or a set of puzzle states' string
        representations, whose puzzle states can't be any part of the path to
        the solution.

        """
        if seen is None:
            seen = set()
        if puzzle.fail_fast():
            return []
        else:
            lst = puzzle.extensions()
            potentials = Queue()
            for i in lst:
                if not i.fail_fast() and not i.__str__() in seen:
                    potentials.enqueue([puzzle] + [i])

            while not potentials.is_empty():
                path = potentials.dequeue()
                if path[-1].is_solved():
                    return path
                potentials = _check_extensions(path[-1], potentials, path,
                                               seen)
            return []
Beispiel #13
0
def remove_all_but_one(queue: Queue) -> None:
    """Remove all items from the given queue except the last one.

    Precondition: <queue> contains at least one item.
                  or: not queue.is_empty()

    >>> queue = Queue()
    >>> queue.enqueue(1)
    >>> queue.enqueue(2)
    >>> queue.enqueue(3)
    >>> remove_all_but_one(queue)
    >>> queue.is_empty()
    False
    >>> queue.dequeue()
    3
    >>> queue.is_empty()
    True
    """
    stack_help = Stack()
    while not queue.is_empty():
        stack_help.push(queue.dequeue())
    queue.enqueue(stack_help.pop())