class Stack: def __init__(self, limit): self.q1 = Queue(limit) self.q2 = Queue(limit) self.limit = limit self.curr_size = 0 def push(self, x): self.curr_size += 1 self.q2.enqueue(x) while not self.q1.isEmpty(): self.q2.enqueue(self.q1.dequeue()) # swap the names of two queues self.q1, self.q2 = self.q2, self.q1 def pop_(self): if (self.q1.isEmpty()): print("Stack Underflow") return self.curr_size -= 1 return self.q1.dequeue() def size(self): return self.curr_size def display(self): print("Stack:") for elem in self.q1.queue[::-1]: print("\t", elem)
def word2vid(keyword): keys = getkeys() consumer_key = keys[0] consumer_secret = keys[1] access_key = keys[2] access_secret = keys[3] line = keyword words = line.split(',') q = Queue(words) video_num = 0 print(q.isEmpty()) print(q.length()) while not q.isEmpty(): word = q.items[0] image0 = "images/" + str(video_num) + "-%01d.png" video = word + ".avi" tweets = gettweets(word, consumer_key, consumer_secret, access_key, access_secret) makeImages(video_num, tweets) video_num = video_num + 1 subprocess.call( ['ffmpeg', '-y', '-framerate', '.1', '-i', image0, video]) q.queuedown() return keyword
class AnimalQueue(object): def __init__(self): self.cat_queue = Queue() self.dog_queue = Queue() self.time = 0 def enqueue(self, animal): if type(animal) is Dog: self.dog_queue.add(animal) elif type(animal) is Cat: self.cat_queue.add(animal) else: raise ValueError("invalid type") animal.order = self.time self.time += 1 def dequeueDog(self): return self.dog_queue.remove() def dequeueCat(self): return self.cat_queue.remove() def dequeueAny(self): if self.dog_queue.isEmpty(): return self.dequeueCat() elif self.cat_queue.isEmpty(): return self.dequeueDog() topDog = self.dog_queue.peek() topCat = self.cat_queue.peek() if topDog.order < topCat.order: return self.dequeueDog() else: return self.dequeueCat()
def imprimeNiv(self): s = "" nodo = self.node if (nodo is None): return q1 = Queue() q2 = Queue() q1.enqueue(self.node) while (not q1.isEmpty()) or (not q2.isEmpty()): while (not q1.isEmpty()): nodo = q1.dequeue() s = s + str(nodo.key) + " " #print(nodo.key) if (nodo.left.node is not None): q2.enqueue(nodo.left.node) if (nodo.right.node is not None): q2.enqueue(nodo.right.node) s = s + "\n" #print("\n") while (not q2.isEmpty()): nodo = q2.dequeue() s = s + str(nodo.key) + " " #print(nodo.key) if (nodo.left.node is not None): q1.enqueue(nodo.left.node) if (nodo.right.node is not None): q1.enqueue(nodo.right.node) s = s + "\n" #print("\n") return s
def testAttr_empty_enqeue(self): queue = Queue() self.assertTrue(queue.isEmpty()) for i in range(0, 10): queue.enqeue(i) self.assertFalse(queue.isEmpty())
def testAttr_empty_dequeue(self): for s in range(5, 10): queue = Queue() self.assertTrue(queue.isEmpty()) for i in range(0, s): queue.enqeue(i) for i in range(0, s): self.assertFalse(queue.isEmpty()) queue.dequeue() self.assertTrue(queue.isEmpty())
def radixSort(nums): """ :param nums: Takes a list of numbers as a string :return: Returns the numbers in ascending order """ if nums is None or len(nums) < 1: return nums mainQ = Queue() binQs = [] # Add all the numbers in the main Queue for n in nums: mainQ.enqueue(n) # create an array of Queues and initialize them - bin 0 to 9 for i in range(10): binQs.append(Queue()) # get the max length of digits in any input number - this will decide the # outer iteration we need to do in our radix sort implementation maxLen = len(nums[0]) for i in range(1, len(nums)): if len(nums[i]) > maxLen: maxLen = len(nums[i]) # we need to iterate maxLen times ie length of the biggest number (in # digits) for i in range(1, maxLen + 1): visited = [] # below iteration includes only numbers of digit length i while not mainQ.isEmpty(): val = mainQ.dequeue() if i > len(val): visited.append(val) continue r = val[-i] # get the ith index from last r = int(r) binQs[r].enqueue(val) for v in visited: mainQ.enqueue(v) for i in range(10): while not binQs[i].isEmpty(): mainQ.enqueue(binQs[i].dequeue()) result = [] while not mainQ.isEmpty(): result.append(mainQ.dequeue()) return result
def crawl(self): f = FileHandling("crawl_all_links.txt") q = Queue() count = 0 depth = 0 q.enqueue(self.mainurl) while not q.isEmpty(): cURL = q.dequeue() time.sleep(1) source = requests.get(cURL) soup = BeautifulSoup(source.text,'html.parser') #print(cURL) count += 1 for link in soup.findAll("a"): #print(link.get("href")) ln = link.get("href") if ln is not None: full_url=self.filter(link.get("href")) if full_url != "": print(full_url) f.log_msg(full_url) q.enqueue(full_url) count+=1 depth+=1 if depth >= self.depth or count >= self.mcount: break print("Number of URL crawled:",count,"Depth of crawled data:",depth)
def main(): for i in range(p.Runs): clock = 0 # set clock to 0 at the start of the simulation if p.hasTrans: if p.Ttechnique == "Light": Transaction.create_transactions_light( ) # generate pending transactions elif p.Ttechnique == "Full": Transaction.create_transactions_full( ) # generate pending transactions Node.generate_gensis_block( ) # generate the gensis block for all miners Scheduler.initial_events() # initiate initial events to start with while not Queue.isEmpty() and clock <= p.simTime: next_event = Queue.get_next_event() clock = next_event.time # move clock to the time of the event Event.run_event(next_event) Queue.remove_event(next_event) Consensus.freshness_preferred( ) # apply the longest chain to resolve the forks Results.calculate( ) # calculate the simulation results (e.g., block statstics and miners' rewards) ########## reset all global variable before the next run ############# Results.reset() # reset all variables used to calculate the results Node.resetState( ) # reset all the states (blockchains) for all nodes in the network print("Percentage of blocks mined by the attacker: ", (p.attacker_blocks / float(p.Runs)))
def ClinicSim(w): # simulation for doctor clinic Doctor0 = Doctor() patientQ = Queue() # creating The queue TimeWaiting = [] # create the waiting times alist for currentsec in range( w): # w is the time we enter ( 4 hours = 4*60*60 second) if random.randrange( 1, 361 ) == 360: #checks the probability of arrival of a patient at any given second patient = Patient(currentsec) #creating a file for the patient patientQ.enqueue(patient) # adding the patient to the queue if not Doctor0.busy() and not patientQ.isEmpty( ): # check if the doctor is not busy and if there is a patient nextp = patientQ.dequeue() # delete patient from queue TimeWaiting.append( nextp.waittime(currentsec) ) #calculate the waiting time then add it to the list of waiting times Doctor0.Nextp(nextp) #let the patient enter to the doctor Doctor0.tick() #checks for patients still at the doctor averagewait = sum(TimeWaiting) / len( TimeWaiting) # calculate the average wait print("Average Wait ", averagewait, " secs", patientQ.size(), " tasks remaining.")
def breadth_first_search(graph, root): graph_t = [node for node in graph if node != root] for node in graph_t: node.color = "white" node.distance = float('inf') node.parent = None root.color = "gray" root.distance = 0 root.parent = None Q = Queue() print "Start conditions:" print("graph: " + str(graph)) print("Q: " + str(Q)) Q.enqueue(root) # pdb.set_trace() while not Q.isEmpty(): print "Iteration:" u = Q.dequeue() for node in u.adjacent: v = getAssociatedNode(graph, node) if v.color == "white": v.color = "gray" v.distance = u.distance + 1 v.parent = u Q.enqueue(v) print("graph: " + str(graph)) print("Q: " + str(Q)) u.color = "black"
def simulation(numSeconds, pagesPerMinute): labprinter = Printer(pagesPerMinute) printQueue = Queue() waitingtimes = [] complete = [] # total time is 1 hour for currentSecond in range(numSeconds): print('currentSecond: ', currentSecond) if newPrintTask(): # if task is created, go into the Queue to wait task = Task(currentSecond) # timestamp for this task printQueue.enqueue(task) print('>>printQueue', printQueue) print('waitingtimes: ', waitingtimes) # add task if (not labprinter.busy()) and (not printQueue.isEmpty()): nexttask = printQueue.dequeue() # waiting time before printing: currentSecond - nexttask.timestamp waitingtimes.append(nexttask.waitTime(currentSecond)) print('>>printQueue', printQueue) print('waitingtimes for all tasks: ', waitingtimes) labprinter.startNext(nexttask) complete.append(nexttask) print('>>complete tasks and next task: ', complete) # start printing # when the timeremaining is 0 then the printer is available labprinter.tick() if waitingtimes != []: averageWait = sum(waitingtimes) / len(waitingtimes) print("Average Wait %6.2f secs %3d tasks remaining" % (averageWait, printQueue.size()))
def simulation(numSeconds, pagesPerMinute): labprinter = Printer(pagesPerMinute) printQueue = Queue() waitingtimes = [] number = 0 # 用循环模拟每一秒钟的情况 for currentSecond in range(numSeconds): # 有新任务时,任务入队 if newPrintTask(): number += 1 task = Task(currentSecond, number) logging.info('第{}秒,任务{}进入打印队列, 共{}页'.format(currentSecond, task.number, task.pages)) printQueue.enqueue(task) # 当打印机不忙,打印队列不为空时,开始下一个任务 if (not labprinter.busy()) and (not printQueue.isEmpty()): nexttask = printQueue.dequeue() waittime = nexttask.waitTime(currentSecond) logging.info('第{}秒,任务{}开始打印,等待了{}秒。'.format(currentSecond, task.number, waittime)) waitingtimes.append(waittime) labprinter.startNext(nexttask) # 执行打印逻辑 当前任务剩余时间 -1, 为0时结束任务 labprinter.tick(currentSecond) averageWait = sum(waitingtimes) / len(waitingtimes) logging.info("共执行了{}项打印任务,平均等待时间为{}秒, 打印队列里还有{}项任务".format\ (number, averageWait, printQueue.size()))
def BFS(graph): sequence = "" number_of_node = len(graph.keys()) # print("no nodes ",number_of_node) graph_queue = Queue(number_of_node) keys = list(graph.keys()) # print("keys: ",keys) graph_queue.enqueue(keys[0]) visited = {key: 0 for key in keys} visited[keys[0]] = 1 while (not graph_queue.isEmpty()): # print("queue ",graph_queue.display()) node = graph_queue.dequeue() # print("node ",node) sequence += str(node) child_nodes = graph[node] # print("child:",child_nodes) for nodes in child_nodes: if not visited[nodes]: graph_queue.enqueue(nodes) visited[nodes] = 1 # print("visited: ",visited) return sequence
def crawl_images(self,number): #f = FileHandling("crawl_all_links.txt") q = Queue() count = 0 q.enqueue(self.mainurl) while not q.isEmpty(): cURL = q.dequeue() time.sleep(1) source = requests.get(cURL) soup = BeautifulSoup(source.text,'html.parser') #print(cURL) for im in soup.findAll("img"): im_ln = im.get("src") if im_ln is not None: print(self.imgfilter(im_ln)) IMAGE = im_ln.rsplit('/',1)[1] try: urllib.request.urlretrieve(self.imgfilter(im_ln), self.imageout+IMAGE) count+=1 except: print("Invalid url...Ignoring") for link in soup.findAll("a"): #print(link.get("href")) ln = link.get("href") if ln is not None: #print(ln) full_url=self.filter(link.get("href")) if full_url != "": q.enqueue(full_url) if count > number: break print("Number of Images crawled:",count)
def crawl_word(self,word): f = FileHandling("crawl_"+word+".txt") q = Queue() count = 0 depth = 0 q.enqueue(self.mainurl) while not q.isEmpty(): cURL = q.dequeue() #time.sleep(1) source = requests.get(cURL) soup = BeautifulSoup(source.text,'html.parser') if soup.find(text=re.compile(word, re.I)) is not None: print(cURL) f.log_msg(cURL) count+=1 for link in soup.findAll("a"): #print(link.get("href")) ln = link.get("href") if ln is not None: #print(ln) full_url=self.filter(link.get("href")) if full_url != "": q.enqueue(full_url) if count > self.mcount: break print("Number of URL crawled:",count,"Depth of crawled data:",depth)
def testEmptyQueue(self): queue = Queue() self.assertFalse(queue.hasOne()) self.assertTrue(queue.isEmpty()) self.assertFalse(queue.isFull()) self.assertEqual(queue.size(), 0)
def breadthFirst(tree): queue = Queue() queue.add(tree) while not (queue.isEmpty()): node = queue.remove() print(node.data) children = node.getChildren() for child in children: queue.add(child)
class AnimalShelter(): def __init__(self): self.cats = Queue() self.dogs = Queue() def enqueue(self, animal): if animal.__class__ == Cat: self.cats.add(animal.name) else: self.dogs.add(animal.name) def dequeueAny(self): if not self.dogs.isEmpty(): return self.dequeueDog() else: self.dequeueCat() def dequeueCat(self): if self.cats.isEmpty(): return None else: cat = self.cats.peek() self.cats.remove() return cat def dequeueDog(self): if self.dogs.isEmpty(): return None else: dog = self.dogs.peek() self.dogs.remove() return dog def print_shelter(self): print() print('Our Cats : ') for i in self.cats.my_queue: print(i) print() print('Our Dogs : ') for i in self.dogs.my_queue: print(i) print()
def levelOrderTraversal(root): qu = Queue() qu.enqueue(root) while not qu.isEmpty(): node = qu.dequeue() print(node.data,end=" ") if node.left: qu.enqueue(node.left) if node.right: qu.enqueue(node.right)
def isConnectedBFSHelper(graph, node1Key, node2Key): node1 = graph.getNodeByKey(node1Key) q = Queue() q.enqueue(node1) while not q.isEmpty(): node = q.dequeue() node.isChecked = True for eachNode in node.adjacents: if eachNode.key == node2Key: return True if not eachNode.isChecked: q.enqueue(eachNode)
def levelOrder(self): """Breadth-First Traversal""" from Queue import Queue q = Queue() q.enqueue(self.root) while not q.isEmpty(): node = q.dequeue() print node.value if node.left: q.enqueue(node.left) if node.right: q.enqueue(node.right)
def bfs(g, s): visited = [] st = Queue() st.enqueue(s) #Assuming s is in g while not st.isEmpty(): cn = st.dequeue() if cn not in visited: visited.append(cn) for c in g.children(cn): if c not in visited: st.enqueue(c) return visited
def testSeq2Empty(self): #Constructor queue = Queue() #Reporter : La queue est vide self.assertTrue(queue.isEmpty()) #Transformer : Une queue vide doit lancer une erreur si on essaie de retirer le premier élément self.assertRaises(ValueError, queue.dequeue) #Reporter : La queue est vide self.assertTrue(queue.isEmpty()) #Transformer : Ajoutons l'élément 0 à la queue queue.enqeue(0) #Reporter : La queue n'est pas vide self.assertFalse(queue.isEmpty()) #Other : Une queue contenant un seul élément doit lancer une erreur si on essaie de récupérer le dernier élément self.assertRaises(ValueError, queue.check_last)
def testSeq1Empty(self): #Constructor queue = Queue() #Reporter : La queue est vide self.assertTrue(queue.isEmpty()) #Transformer : Ajoutons l'élément 0 à la queue queue.enqeue(0) #Reporter : La queue n'est pas vide self.assertFalse(queue.isEmpty()) #Transformer : Retirons l'élément 0 de la queue self.assertEqual(str(queue.dequeue()), str(0)) #Reporter : La queue est vide self.assertTrue(queue.isEmpty()) #Other : Une queue contenant vide doit lancer une erreur si on essaie de récupérer le premier élément self.assertRaises(ValueError, queue.check_first)
def _bfs(self, graph, s): q = Queue() self.makred[s] = True q.enqueue(s) while not q.isEmpty(): v = q.dequeue() for w in graph.adj(v): if self.makred[w] is False: self.edgeTo[w] = v self.makred[w] = True q.enqueue(w)
def BFS(self): s = Queue() s.enqueue(self.root) while not s.isEmpty(): node = s.dequeue() if node is None: continue print(node.value, end=' ') s.enqueue(node.right) s.enqueue(node.left) print()
def levelOrderTraversal(root): q = Queue(13) q.enqueue(root) traversal = [] while not q.isEmpty(): node = q.dequeue() traversal.append(node.data) node = node.getFirstChild() while node is not None: q.enqueue(node) node = node.getNextSibling() return traversal
def test_queue(self): myQueue = Queue(10) self.assertIsNone(myQueue.dequeue()) self.assertTrue(myQueue.isEmpty()) self.assertFalse(myQueue.isFull()) self.assertIsNone(myQueue.peek()) myQueue.enqueue(1) myQueue.enqueue(2) myQueue.enqueue(3) self.assertEqual(myQueue.dequeue(), 1) self.assertEqual(myQueue.dequeue(), 2) self.assertEqual(myQueue.dequeue(), 3)
def _bfs(self,graph,s): q = Queue() self.makred[s] = True q.enqueue(s) while not q.isEmpty(): v = q.dequeue() for w in graph.adj(v): if self.makred[w] is False: self.edgeTo[w] = v self.makred[w] = True q.enqueue(w)
class CallCenter: def __init__(self): self.employees = { 'respondents': [], 'managers': [], 'directors': [] } self.incoming_calls = Queue() def add_calls_to_waiting_list(self, call): self.incoming_calls.enqueue(call) def search_for_availability(self, employee_type): e = 0 while not self.employees[employee_type][e].is_available and \ e < len(self.employees[employee_type]): e += 1 return e def dispatch_call(self): """ Assigns respondents to calls in the queue type: None return type: Respondent """ while not self.incoming_calls.isEmpty(): call = self.incoming_calls.dequeue() # find a respondent who is available avbl_respondent = self.search_for_availability(self, 'respondents') # case: no respondents are available # dispatch to first available manager if avbl_respondent == len(self.employees['respondents']): avbl_manager == self.search_for_availability(self, 'managers') # case: no managers are available # dispatch to first available director if avbl_manager == len(self.employees['directors']): avbl_director = self.search_for_availability('directors') # case: we found an available manager # assign their availability to False else: self.employees['managers'][avbl_manager].is_available = False self.employees['managers'][avbl_manager].calls.append(call) # case: we found an available respondent # assign their availability to False else: self.employees['respondents'][avbl_respondent].is_available = False self.employees['respondents'][avbl_respondent].calls.append(call)
def bfsFromVertex(graph,val,visited): visited.add(val) print(val) q = Queue() q.enqueue(val) while(not q.isEmpty()): v = q.dequeue() if(v in graph.__dict.keys()): for adjV in graph.__dict[v]: if(adjV not in visited): print(adjV) visited.add(adjV) q.enqueue(adjV)
def BFS(self, vertex): print("BFS traversal of this graph starting from %d is:" % vertex) visitedStatus = [False for i in range(self.size)] traversalQueue = Queue(self.size) traversalQueue.enqueue(vertex) visitedStatus[vertex] = True while traversalQueue.isEmpty() is False: element = traversalQueue.dequeue() print(element) for v, w in self.adjacencyList[element]: if visitedStatus[v] is False: traversalQueue.enqueue(v) visitedStatus[v] = True
def levelOrder(self,a): q = Queue() r = a while r is not None: print(r.root.data) if r.root.left is not None: q.add(r.root.left) if r.root.right is not None: q.add(r.root.right) if q.isEmpty(): print("empty") r = None else: r = q.delete()
def testQueue(): a = Queue() #Testing isEmpty() print(a.isEmpty()) #Testing adding for i in range(10): a.add(i) a.displayQueue() #Testing removing a.remove() a.displayQueue()
def bfs1(graph,root,target): q = Queue() visited = [] q.enqueue(root) while not q.isEmpty(): removeNode = q.dequeue() if removeNode == target: return True elif v not in visited: for edge in graph[v]: if v not in visited: q.enqueue(edge) visited.append(v) return False
def dfs (self): q = Queue() arr = [] q.enqueue (self) while ( not q.isEmpty()): item = q.dequeue() arr.append (item.value) left = item.left right = item.right if (left is not None): q.enqueue (left) if (right is not None): q.enqueue (right) return arr
def simulation(seconds, ppm): printQueue = Queue() waitingtimes = [] printer = Printer(ppm) for currentSecond in range(seconds): if newPrintTask(): printQueue.enqueue(Task("Task"+str(currentSecond), currentSecond)) if (not printer.busy()) and (not printQueue.isEmpty()): nexttask = printQueue.dequeue() waitingtimes.append(nexttask.getWaitTime(currentSecond)) printer.nextTask(nexttask) printer.tick() lenWaitTime = len(waitingtimes) averageWait=sum(waitingtimes)/lenWaitTime print("Average Wait %6.2f secs %3d tasks remaining."%(averageWait,printQueue.size()))
class Queue_Animal_array(object): def __init__(self): self.cat = Queue() self.dog = Queue() self.count = 0 def animal_enqueue(self, item): animal = Animal(item, self.count) if animal.cat_or_dog() == "cat": self.cat.enqueue(animal) self.count += 1 elif animal.cat_or_dog() == "dog": self.dog.enqueue(animal) self.count += 1 else: return None def animal_dequeueAny(self): if self.cat.isEmpty() and self.dog.isEmpty(): return None elif self.cat.isEmpty() and not self.dog.isEmpty(): return self.dog.dequeue() elif not self.cat.isEmpty() and self.dog.isEmpty(): return self.cat.dequeue() else: cat = self.cat.peak().id dog = self.dog.peak().id if cat<dog: return self.cat.dequeue() else: return self.dog.dequeue() def animal_dequeueCat(self): if self.cat.isEmpty(): return None else: return self.cat.dequeue() def animal_dequeueDog(self): if self.dog.isEmpty(): return None else: return self.dog.dequeue()
def bfs(self, v): searchOrders = [] parent = len(self.vertices) * [-1] # Initialize parent[i] to -1 queue = Queue() # the Queue class is defined in Chapter 12 isVisited = len(self.vertices) * [False] queue.enqueue(v) # Enqueue v isVisited[v] = True # Mark it visited while not queue.isEmpty(): u = queue.dequeue() # Dequeue to u searchOrders.append(u) # u searched for w in self.neighbors[u]: if not isVisited[w]: queue.enqueue(w) # Enqueue w parent[w] = u # The parent of w is u isVisited[w] = True # Mark it visited return Tree(v, parent, searchOrders, self.vertices)
def simulation(numseconds, pageperminute): labprinter = Printer(pageperminute) printerQueue = Queue() waitingtimes = [] for currentseconds in range(numseconds): if newPrintTask(): task = Task(currentseconds) printerQueue.enqueue(task) if (not labprinter.busy()) and (not printerQueue.isEmpty()): nextTask = printerQueue.dequeue() waitingtimes.append(nextTask.waitTime(currentseconds)) labprinter.pickNextTask(nextTask) labprinter.tick() averageWait = sum(waitingtimes)/len(waitingtimes) print("Average Wait %6.2f secs %3d tasks remaining."%(averageWait,printerQueue.size()))
class TestQueue(unittest.TestCase): def setUp(self): self.queue = Queue() def test_0(self): print("{} Can create Queue object".format(inspect.stack()[0][3])) self.assertTrue(type(self.queue) is Queue) def test_1(self): print("{} Newly created queues should be empty".format(inspect.stack()[0][3])) self.assertTrue(self.queue.isEmpty()) def test_2(self): print("{} After one enqueue, queue size should be one".format(inspect.stack()[0][3])) self.queue.enqueue(1) self.assertEqual(self.queue.getSize(), 1) def test_3(self): print("{} After one enqueue and one dequeue, should be empty".format(inspect.stack()[0][3])) self.queue.enqueue(1) self.queue.dequeue() self.assertEqual(self.queue.getSize(),0) def test_4(self): print("(S) {} When enqueued passed limit, queue overflows".format(inspect.stack()[0][3])) def test_5(self): print("{} When dequeued passed limit, queue underflows".format(inspect.stack()[0][3])) with self.assertRaises(Queue.Underflow): self.queue.dequeue() def test_6(self): print("{} When two values are enqueued then one is dequeued, size is one".format(inspect.stack()[0][3])) self.queue.enqueue(1) self.queue.enqueue(2) self.queue.dequeue() self.assertEqual(self.queue.getSize(),1) def test_7(self): print("{} When 1 is enqueued 1 is dequeued".format(inspect.stack()[0][3])) self.queue.enqueue(1) self.assertEqual(self.queue.dequeue(),1) def test_8(self): print("{} When 1 and 2 are enqueued 1 and 2 are dequeued".format(inspect.stack()[0][3])) self.queue.enqueue(1) self.queue.enqueue(2) self.assertEqual(self.queue.dequeue(),1) self.assertEqual(self.queue.dequeue(),2) def test_9(self): print("(S) {} When creating queue with negative size, should throw IllegalCapacity".format(inspect.stack()[0][3])) def test_10(self): print("(S) {} When Creating queue with zero capacity, any enqueue should overflow".format(inspect.stack()[0][3])) def test_11(self): print("{} When 1 is enqueued, 1 is on top".format(inspect.stack()[0][3])) self.queue.enqueue(1) self.assertEqual(self.queue.top(),1) def test_12(self): print("{} When queue is empty, top throws empty".format(inspect.stack()[0][3])) with self.assertRaises(Queue.Empty): self.queue.top() def test_13(self): print("(S) {} With zero capacity queue, top throws empty".format(inspect.stack()[0][3])) def test_14(self): print("{} Given queue with 1 2 enqueued, find 1 and 2".format(inspect.stack()[0][3])) self.queue.enqueue(1) self.queue.enqueue(2) self.assertEqual(self.queue.find(1),0) self.assertEqual(self.queue.find(2),1) def test_15(self): print("{} Given a queue with no 2, find(2) returns null".format(inspect.stack()[0][3])) self.assertEqual(self.queue.find(2),None)