def list_of_depths(root): """ This solution is a modification of breadth first search. """ q = MyQueue() depth_lists = [] seen = [] q.add((root, 0)) seen.append(root) while not q.is_empty(): q.print_queue() node, depth = q.remove().data try: depth_lists[depth].insert(node) except IndexError: depth_lists.append(LinkedList()) depth_lists[depth].insert(node) adjacent_nodes = [node.left, node.right] for child in adjacent_nodes: if child is not None and child not in seen: seen.append(child) q.add((child, depth + 1)) return depth_lists
def get_binary_numbers(numbers): q = MyQueue() q.enqueue('1') for i in range(numbers): front = q.front() print(" ", front) q.enqueue(front + "0") q.enqueue(front + "1") q.dequeue()
def setUp(self): """Test case set up.""" self.queue = MyQueue() self.queue.enqueue({ 'company': 'Wal mart', 'timestamp': '15 apr, 11.01 AM', 'price': 131.10 }) self.queue.enqueue({ 'company': 'Wal mart', 'timestamp': '15 apr, 11.02 AM', 'price': 132 }) self.queue.enqueue({ 'company': 'Wal mart', 'timestamp': '15 apr, 11.03 AM', 'price': 135 })
def bf_search(root, visit): q = MyQueue() root.marked = True q.add(root) while not q.is_empty(): node = q.remove().data visit(node) for adjacent_node in node.adjacent: if adjacent_node.marked is False: adjacent_node.marked = True q.add(adjacent_node)
def build_order(projects, dependencies): """ The solution to this problem is a topological search. It builds a graph from the tasks and dependencies, finds the independent tasks, and then performs a breadth first search to identify a legal topological ordering. """ #Build a graph where each projects is a node #and each dependency is a directed edge from #the dependent project to the earlier project. node_dict = {x: GraphNode(val=x) for x in projects} for dependency in dependencies: first, second = dependency node_dict[second].add_edge(node_dict[first]) g = Graph() for node in node_dict.values(): g.add(node) nodes = node_dict.values() independents = [node for node in nodes if len(node.adjacent)==0] for node in nodes: #Delete all edges from node. node.adjacenct = [] for dependency in dependencies: #Flip edge from original setup. Now projects that #come first point to ones that should follow first, second = dependency node_dict[first].add_edge(node_dict[second]) q = MyQueue() for node in independents: q.add(node) task_list = [] while not q.is_empty(): node = q.remove().data task_queue.append(node.val) node.marked = True for adjacent_node in node.adjacent: if adjacent_node.marked is False: adjacent_node.marked = True q.add(adjacent_node) return task_list
class AnimalShelter: def __init__(self): self.dog_queue = MyQueue() self.cat_queue = MyQueue() self.order = 0 def enqueue(self, animal): self.order += 1 if animal == 'dog': self.dog_queue.add(order) elif animal == 'cat': self.cat_queue.add(order) def dequeueDog(self): return self.dog_queue.remove() def dequeueCat(self): return self.cat_queue.remove() def dequeueAny(self): if self.cat_queue.peek() < self.dog_queue.peek(): return self.cat_queue.remove() else: return self.dog_queue.remove()
class TestQueue(unittest.TestCase): """Queue test case.""" def setUp(self): """Test case set up.""" self.queue = MyQueue() self.queue.enqueue({ 'company': 'Wal mart', 'timestamp': '15 apr, 11.01 AM', 'price': 131.10 }) self.queue.enqueue({ 'company': 'Wal mart', 'timestamp': '15 apr, 11.02 AM', 'price': 132 }) self.queue.enqueue({ 'company': 'Wal mart', 'timestamp': '15 apr, 11.03 AM', 'price': 135 }) def test_enqueue_method(self): """Test that are elements in the queue and .is_empty() method""" q = self.queue self.assertFalse(q.is_empty()) def test_front_method(self): """Test .front() method comparing front with and object.""" q = self.queue object_ = { 'company': 'Wal mart', 'timestamp': '15 apr, 11.01 AM', 'price': 131.10 } self.assertEqual(q.front(), object_) def test_dequeue_method(self): q = self.queue object_ = { 'company': 'Wal mart', 'timestamp': '15 apr, 11.01 AM', 'price': 131.10 } self.assertEqual(q.dequeue(), object_) self.assertNotIn(object_, q.buffer) def test_size_method(self): q = self.queue self.assertEqual(q.size(), 3)
def reverseK(queue, k): if k < 0 or k > queue.size() or queue.is_empty(): return None stack = [] out = MyQueue() # deq k times onto a stack # pop from stack k times and enq for i in range(k): stack.append(queue.dequeue()) print(stack) while len(stack) > 0: out.enqueue(stack.pop()) while queue.size() > 0: out.enqueue(queue.dequeue()) return out
"""Design a food ordering system where your python program will run two threads, + Place Order: This thread will be placing an order and inserting that into a queue. This thread places new order + every 0.5 second. (hint: use time.sleep(0.5) function) + Serve Order: This thread will server the order. All you need to do is pop the order out of the queue and print it. +This thread serves an order every 2 seconds. Also start this thread 1 second after place order thread is started.""" # Queue from queues import MyQueue # Utils import threading import time q = MyQueue() def place_orders(orders): """Process the orders.""" for order in orders: print('Placing order:', order) q.enqueue(order) time.sleep(0.5) def serve_orders(): """Serve the orders and remove it from the queue.""" time.sleep(1) while q.size() != 0: print('Serving:', q.dequeue())
def reverseK(queue, k): if k < 0 or k > queue.size() or queue.is_empty(): return None stack = [] out = MyQueue() # deq k times onto a stack # pop from stack k times and enq for i in range(k): stack.append(queue.dequeue()) print(stack) while len(stack) > 0: out.enqueue(stack.pop()) while queue.size() > 0: out.enqueue(queue.dequeue()) return out # Driving code inputq = MyQueue() inputq.set([1,2,3,4,5,6,7,8,9,10]) print(reverseK(inputq, 5))
def __init__(self): self.dog_queue = MyQueue() self.cat_queue = MyQueue() self.order = 0