def simulation(seconds, print_speed): printer = Printer(print_speed) print_queue = MyQueue() wait_time_list = [] for current_second in range(seconds): if Task.new_task(): task = Task(current_second) print_queue.enqueue(task) if (not printer.busy()) and (not print_queue.is_empty()): new_task = print_queue.dequeue() wait_time_list.append(new_task.wait_time(current_second)) printer.start_next(new_task) printer.tick() average_wait_time = sum(wait_time_list) / len(wait_time_list) print( f'Average wait {average_wait_time:6.2f}, {print_queue.size():3d} tasks remaining' )
def list_of_depths(self): """ Create a linked list of all the nodes at each depth. For example, a tree with depth D has D linked lists. """ queue = MyQueue() the_dict = defaultdict(list) level = 0 queue.push((self, level)) while (queue.is_empty() == False): node, level = queue.pop() the_dict[level].append(node.key) if (node.left != None): queue.push((node.left, level + 1)) if (node.right != None): queue.push((node.right, level + 1)) return the_dict
def breadth_first_search(graph, start_node, destination_node): """ BFS. Make use of a queue, and make sure to mark nodes as visited! TODO: Return the path and its cost. """ graph.reset_visited() q = MyQueue() start_node.visited = True q.push(start_node) while (q.is_empty() == False): node = q.pop() if (node == destination_node): return True for adjacent in node.adjacents: q.push(adjacent) return False