def __init__(self, length: int = DEFAULT_CAPACITY): """ complexity: O(n) """ Queue.__init__(self) self.front = 0 self.rear = 0 self.array = [None] * length
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()
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()
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)
def _check_extensions(p: Puzzle, q: Queue, path: List[Puzzle], seen: Optional[Set[str]] = None) -> Queue: """ Checks the extensions of the inputted puzzle and returns a new queue with all the extensions that do not fail fast and are not in seen. Also modifies the path list so that it contains the new extension as a path or removes all paths that led to the extension that fails fast. """ for p2 in p.extensions(): if not p2.fail_fast() and not p2.__str__() in seen: q.enqueue(path + [p2]) seen.add(p2.__str__()) else: seen.add(p2.__str__()) return q
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()
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())
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 """ while not queue.is_empty(): b1 = queue.dequeue() queue.enqueue(b1)
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)
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 []
def construct_from_list(values: List[List[Union[str, int]]]) -> ExprTree: """ Construct an expression tree from <values>. See the handout for a detailed explanation of how <values> encodes the expression tree. Hint: We have provided you with the helper method ExprTree.append You will likely want to use this method. Precondition: <values> encodes a valid expression tree >>> example = [[5]] >>> exp_t = construct_from_list(example) >>> exp_t == ExprTree(5, []) True >>> print(exp_t) 5 >>> print(ExprTree(5, [])) 5 >>> example = [['+'], [3, 'a']] >>> exp_t = construct_from_list(example) >>> subtrees = [ExprTree(3, []), ExprTree('a', [])] >>> exp_t == ExprTree('+', subtrees) True """ if not values: return ExprTree(None, []) copy = values[:] current_level = Queue() first = copy.pop(0)[0] if first not in OPERATORS: return ExprTree(first, []) else: result = ExprTree(first, []) current_level.enqueue(result) while copy: lst = copy.pop(0) tree = current_level.dequeue() for element in lst: subtree = ExprTree(element, []) tree.append(subtree) if element in OPERATORS: current_level.enqueue(subtree) return result
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 []
def construct_from_list(values: List[List[Union[str, int]]]) -> ExprTree: """ Construct an expression tree from <values>. See the handout for a detailed explanation of how <values> encodes the expression tree. Hint: We have provided you with the helper method ExprTree.append You will likely want to use this method. Precondition: <values> encodes a valid expression tree >>> example = [[5]] >>> exp_t = construct_from_list(example) >>> exp_t == ExprTree(5, []) True >>> print(exp_t) 5 >>> print(ExprTree(5, [])) 5 >>> example = [['+'], [3, 'a']] >>> exp_t = construct_from_list(example) >>> subtrees = [ExprTree(3, []), ExprTree('a', [])] >>> exp_t == ExprTree('+', subtrees) True """ solution = ExprTree(values[0][0], []) temp = Queue() temp.enqueue(solution) lst = values lst.remove(values[0]) for value in values: v = temp.dequeue() for i in value: if i in ["*", "+"]: tree = ExprTree(i, []) temp.enqueue(tree) v.append(tree) else: v.append(ExprTree(i, [])) return solution
def construct_from_list(values: List[List[Union[str, int]]]) -> ExprTree: """ Construct an expression tree from <values>. See the handout for a detailed explanation of how <values> encodes the expression tree. Hint: We have provided you with the helper method ExprTree.append You will likely want to use this method. Precondition: <values> encodes a valid expression tree >>> example = [[5]] >>> exp_t = construct_from_list(example) >>> exp_t == ExprTree(5, []) True >>> print(exp_t) 5 >>> print(ExprTree(5, [])) 5 >>> example = [['+'], [3, 'a']] >>> exp_t = construct_from_list(example) >>> subtrees = [ExprTree(3, []), ExprTree('a', [])] >>> exp_t == ExprTree('+', subtrees) True """ queue = Queue() a = ExprTree(values.pop(0)[-1], []) queue.enqueue(a) for lst in values: gen = queue.dequeue() for i in lst: root = ExprTree(i, []) if i in OPERATORS: queue.enqueue(root) gen.append(root) else: gen.append(root) return a
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 []
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 __init__(self, length: int = DEFAULT_CAPACITY): Queue.__init__(self) self.front = 0 self.rear = 0 self.array = [None] * length
def clear(self) -> None: Queue.clear(self) self.front = 0 self.rear = 0