def _profile_enqueue(queue_size: int, n: int) -> None: """Report the time taken to perform enqueue operations. Specifically, report the time taken to perform a single Queue.enqueue operation on <n> queues, each of size <queue_size>. (We do this on multiple queues to slow down the trials a little.) """ # TODO: implement this function by following the steps in the comments. # Experiment preparation: make a list containing <n> queues, # each of size <queue_size>. The elements you enqueue don't matter. # You can "cheat" here and set your queue's _items attribute # directly to a list of the appropriate size by writing something like # # queue._items = list(range(queue_size)) # # to save a bit of time in setting up the experiment. # First, make a list containing <n> queues of size <queue_size>. # Second, for each of the <n> queues, enqueue a single item. # (Wrap the code in a Timer block to measure the total time taken.) with Timer('profile enqueue'): queue_list = [] queue = Queue() queue._items = list(range(queue_size)) for i in range(n): queue_list.append(queue) for obj in queue_list: obj.enqueue(1)
def _setup_queues(qsize: int, n: int) -> List[Queue]: """Return a list of <n> queues, each of the given size.""" # Experiment preparation: make a list containing <n> queues, # each of size <qsize>. # You can "cheat" here and set your queue's _items attribute directly # to a list of the appropriate size by writing something like # # queue._items = list(range(qsize)) # # to save a bit of time in setting up the experiment. lst = [] for i in range(n): q = Queue() q._items = list(range(qsize)) lst.append(q) return lst
def myBfs(self, S, direction, player, state): # initialize BFS minDistanceFromGoal = state.size + 1 parent = [[None for _ in range(state.size)] for _ in range(state.size)] Q = Queue() for s in S: Q.add(s) parent[s[0]][s[1]] = -1 # BFS loop cnt = 0 while len(Q) > 0: cnt += 1 r, c = Q.remove() for d in tak.DIR: rr = r + d[0] cc = c + d[1] if 0 <= rr < state.size and 0 <= cc < state.size and \ parent[rr][cc] is None and state.is_controlled_by(rr, cc, player): Q.add((rr, cc)) minDistanceFromGoal = min( self.check_possible_path_from_stack( direction, r, c, state, player), minDistanceFromGoal) parent[rr][cc] = (r, c) # check whether the other side was reached r, c, step, reverse = self.getDirectionIndexes(direction, state) for i in range(0, state.size): # maxListOfPath = [] # list of paths maxList = [] # list of coordinates of the subpaths iterationList = range(0, state.size) listOfDistancesFromGoal = [] if reversed: reversed(iterationList) goalPosition = iterationList[0] if r == -1: for row in iterationList: if parent[row][c] is not None: # build the path cur = (row, c) # maxListOfPath.append(self.buildPath(parent, cur)) maxList.append(cur) listOfDistancesFromGoal.append(abs(goalPosition - row)) else: # column for col in iterationList: if parent[r][col] is not None: # build the path cur = (r, col) # maxListOfPath.append(self.buildPath(parent, cur)) maxList.append(cur) listOfDistancesFromGoal.append(abs(goalPosition - col)) if len(maxList) == 1: return listOfDistancesFromGoal[0], minDistanceFromGoal elif len(maxList) > 1: return listOfDistancesFromGoal[self.findFarthestFromCapstone( maxList, state)], minDistanceFromGoal r += step[0] c += step[1] return state.size, minDistanceFromGoal
def bfs(self, S, T, player): # initialize BFS parent = [[None for _ in range(self.size)] for _ in range(self.size)] Q = Queue() for s in S: Q.add(s) parent[s[0]][s[1]] = -1 # BFS loop cnt = 0 while len(Q) > 0: cnt += 1 r, c = Q.remove() for d in DIR: rr = r + d[0] cc = c + d[1] if 0 <= rr and rr < self.size and 0 <= cc and cc < self.size and parent[ rr][cc] == None and self.is_controlled_by( rr, cc, player): Q.add((rr, cc)) parent[rr][cc] = (r, c) # check whether the other side was reached for r, c in T: if parent[r][c] != None: # build the path path = [] cur = (r, c) while cur != -1: path.append(cur) cur = parent[cur[0]][cur[1]] return path return None
def removeTrack(self, trackToRemove): tracklist = self.__mediaQueue newlist = Queue() found = False while tracklist.isEmpty() == False: look = tracklist.peek() if look != trackToRemove: newlist.enqueue(look) tracklist.dequeue() elif look == trackToRemove: found = True tracklist.dequeue() else: if found == False: self.__mediaQueue = newlist raise ValueError ("That track is not in the playlist!") else: self.__mediaQueue = newlist
def get_n_queue(queue_size, n): """ return a list containing n queues """ global result result = [] for i in range(n): result.append(i) for items in range(len(result)): result[items] = Queue(list(range(queue_size))) return result
class MediaPlayer: def __init__(self): self.__mediaQueue = Queue() def addTrack(self, newTrack): self.__mediaQueue.enqueue(newTrack) def __str__(self): return str(self.__mediaQueue) @property def count(self): return self.__mediaQueue.size() def play(self): while self.__mediaQueue.isEmpty() != False: currentTrack = self.__mediaQueue.dequeue() print("Now playing",currentTrack) sec = 1 for s in currentTrack.length: time.sleep(1) print(sec," of ",currentTrack.length," seconds") sec += 1 else: print("There are no tracks in the playlist") def bringToFront(self, fronttrack): tracklist = self.__mediaQueue newlist = Queue() found = False list2 = Queue() while not tracklist.isEmpty(): first = tracklist.peek() if first != fronttrack: list2.addTrack(first) tracklist.dequeue() if first = fronttrack: found = True newlist.enqueue(first) tracklist.dequeue else:
def bringToFront(self, fronttrack): tracklist = self.__mediaQueue newlist = Queue() found = False list2 = Queue() while not tracklist.isEmpty(): first = tracklist.peek() if first != fronttrack: list2.addTrack(first) tracklist.dequeue() if first = fronttrack: found = True newlist.enqueue(first) tracklist.dequeue
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while vertQueue.size() > 0: currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if nbr.getColor() == 'white': nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black')
def BFS(maze, v, goal, came_from): frontier = Queue() frontier.enqueue(v) came_from[v] = None while not frontier.is_empty(): v = frontier.dequeue() if maze[v[0], v[1]] == Maze.EMPTY: if v == goal: return v else: maze[v[0], v[1]] = Maze.OCCUPIED for w in maze.getAllMoves(v[0], v[1]): if maze[w[0], w[1]] == Maze.EMPTY: frontier.enqueue(w) came_from[w] = v return None
def _profile_dequeue(queue_size: int, n: int) -> None: """Report the time taken to perform enqueue operations. Specifically, report the time taken to perform a single Queue.enqueue operation on <n> queues, each of size <queue_size>. (We do this on multiple queues to slow down the trials a little.) """ # TODO: implement this function in a similar way to _profile_enqueue. # Experiment preparation: make a list containing <n> queues, # each of size <queue_size>. # You can "cheat" here and set your queue's _items attribute # directly to a list of the appropriate size by writing something like # # queue._items = list(range(queue_size)) # # to save a bit of time in setting up the experiment. with Timer('profile dequeue'): queue_list = [] queue = Queue() queue._items = list(range(queue_size)) for i in range(n): queue_list.append(queue) for obj in queue_list: obj.dequeue()
def bfs(g, start): ''' After running through BFS, all vertices of the graph will have their color, distance and predecessor from the start. ''' start.set_predecessor(None) start.set_distance(0) vert_queue = Queue() vert_queue.enqueue(start) while vert_queue.size() != 0: cur_vertex = vert_queue.dequeue() for nbr in cur_vertex.get_connections(): if nbr.color == Color.WHITE: nbr.set_color(Color.GRAY) nbr.set_distance(cur_vertex.get_distance() + 1) nbr.set_predecessor(cur_vertex) vert_queue.enqueue(nbr) cur_vertex.set_color(Color.BLACK)
def bfs_no_tunneling(filename, env): # stats max_coverage = 0 nodes_cnt = 0 start_time = time.time() print_time = time.time() - 2 # state queue = Queue() hashes = set() queue.append(env.get_init_state()) # push the initial state while not queue.empty(): state = queue.pop() nodes_cnt = nodes_cnt + 1 if time.time() > print_time + 1: if env.coverage(state) * 100 > max_coverage: max_coverage = env.coverage(state) * 100 history = state.get_history() print_status(filename, -1, int(time.time() - start_time), max_coverage, len(hashes), queue.items, nodes_cnt, len(history), 0) print_time = time.time() nodes_cnt = 0 possible_moves = env.nodes[state.pos].keys() for op in possible_moves: new_state = env.do_step(op=op, state=state) new_state_hash = env.state_hash(new_state) if new_state_hash in hashes: continue if env.goal_reached(new_state): clean_status() return new_state hashes.add(new_state_hash) queue.append(new_state) clean_status() return None
def BFS(G,s): for u in G.getVertices(): if u!=s: u.color='white' u.d=np.inf u.pre=None s.color='gray' s.d=0 s.pre=None Q=Queue() Q.Enqueue(s) while not Q.IsEmpty(): u=Q.Dequeue() for v in u.getConnections(): if v.color=='white': v.color='gray' v.d=u.d+1 v.pre=u Q.Enqueue(v) u.color='black'
from __future__ import print_function import time from myqueue import Queue Q = Queue() Q.append(10) Q.append(20) print(Q.peek()) print(Q.pop()) print(Q.pop()) try: print(Q.pop()) except IndexError as e: print("Error message:", e) # Prints "Queue is empty" i = 10000 values = range(i) start_time = time.time() Q.extend(values) end_time = time.time() - start_time print("Adding {} items took {:1.3f} msecs.".format(i, 1000 * end_time)) for i in range(41):
def radixSortStrings(listOfStrings): ''' Function to sort the items in the listOfStrings using a radixsort algorithm ''' # Create the mainqueue and enqueue the items from the listOfStrings mainqueue = Queue() for item in listOfStrings: mainqueue.enqueue(item) # Calculate the max length so that we know how many iterations we need to do maxLength = 0 auxQ = Queue() for item in range(len(mainqueue)): temp = mainqueue.dequeue() length = len(temp) auxQ.enqueue(temp) if length > maxLength: maxLength = length updateQueue(mainqueue,auxQ) # Initialize an ordered dictionary auxQueuesDictionary that holds 27 auxiliary queues for 27 characters # as keys: ' ' and 26 lower case letters. Make sure the keys are added in # alphabetical order so that when we iterate over the dictinary, keys are # retrieved in alphbetical order. setupAuxQueuesDictionary() auxQueueDictionary.__setitem__(" ",0) for char in string.ascii_lowercase: auxQueueDictionary.__setitem__(char,0) #Set up a for loop that sorts the items from the mainqueue based on # characters at index maxLength, then the characters at index maxLength-1, # maxLength-2, ...index 0. Every time using the auxiliary queues to do the sorting for strng in mainqueue: for index in range(maxLength-1,0,-1): char = charAt(strng,index) auxQueueDictionary.__setitem__(char,strng) for item in auxQueueDictionary temp = auxQueueDictionary.pop() mainqueue.enqueue(temp) sortedList = [] # mainQueue should be sorted. # dequeue the items of the mainqueue into a list and return it for item in range(len(mainqueue)): temp = mainqueue.dequeue() sortedList.append(temp) return sortedList
def hotPotato(namelist, numrounds): namequeue = Queue() for name in namelist: namequeue.enqueue(name) while namequeue.size() > 1: for i in range(numrounds): namequeue.enqueue(namequeue.dequeue()) namequeue.dequeue() return namequeue.dequeue()
from myqueue import Queue myq = Queue() myq.Enqueue('A') myq.Enqueue('B') myq.Enqueue('C') myq.Enqueue('D') myq.Enqueue('A') myq.Enqueue('E') myq.PrintQueue() len_now = myq.queueNo def deleteqA(item): i = 0 while i < len_now: if myq.queue[myq.front + 1] != item: myq.Enqueue(myq.Dequeue()) else: myq.Dequeue() i += 1 def deleteqA2(item):
max_seq_num = transmit_window + 1 receive_window = 1 expected_pkt = 0 frame_to_send = 0 timer_duration = 1000 #in milliseconds total_packets_sent = 0 total_packets_dropped = 0 total_packets_resent = 0 total_packets_received = 0 total_volume_sent = 0 total_volume_received = 0 total_volume_resent = 0 lock = threading.Lock() q = Queue(transmit_window) time_stamp_q = Queue(transmit_window) tempq = Queue(transmit_window) packet_drop_probability = 0.05 ack_drop_probability = 0.05 def should_drop(threshold): temp = random.uniform(0, 1) if (temp <= threshold): return True else: return False client_receiver_address = (socket.gethostbyname(socket.gethostname()), 9998)
def __init__(self): """ Initialize class """ self.queue = Queue() self.start()
class Handler: """ Handler class """ _OPTIONS = { "1": "add_to_queue", "2": "remove_from_queue", "3": "get_first_item", "4": "get_queue_size", "5": "is_queue_empty", "q": "quit" } def __init__(self): """ Initialize class """ self.queue = Queue() self.start() def _get_method(self, method_name): """ Uses function getattr() to dynamically get value of an attribute. """ return getattr(self, self._OPTIONS[method_name]) def _print_menu(self): """ Use docstring from methods to print options for the program. """ menu = "" for key in sorted(self._OPTIONS): method = self._get_method(key) docstring = inspect.getdoc(method) menu += "{choice}: {explanation}\n".format( choice=key, explanation=docstring ) print(chr(27) + "[2J" + chr(27) + "[;H") print(menu) def add_to_queue(self): """ Adds a node to the queue. """ value = input("\nAdd a value: \n>>> ") self.queue.enqueue(value) print(f"{value} has been added.") def remove_from_queue(self): """ Removes the first node from the queue. """ try: print(f"{self.queue.dequeue()} has been removed.") except EmptyQueueException as e: print(f"Error: {e}") def get_first_item(self): """ Prints the value of the first queue node. """ try: print(self.queue.peek()) except EmptyQueueException as e: print(f"Error: {e}") def get_queue_size(self): """ Shows the queue length. """ print(self.queue.size()) def is_queue_empty(self): """ Shows if the queue is empty or not. """ print(self.queue.is_empty()) @staticmethod def quit(): """ Quit the program """ sys.exit() def start(self): """ Start method """ while True: self._print_menu() choice = input("Enter menu selection:\n-> ") try: self._get_method(choice.lower())() except KeyError: print("Invalid choice!") input("\nPress any key to continue ...")
from myqueue import Queue queue1 = Queue() queue1.push("Ranjeet") print(queue1.pop()) print(queue1.pop())
def test_pop(self): q = Queue() self.assertTrue(q.empty()) q.append("1") self.assertFalse(q.empty()) self.assertEqual("1", q.pop()) self.assertTrue(q.empty()) q.append("2") self.assertFalse(q.empty()) q.append("3") q.append("4") q.append("5") q.append("6") self.assertFalse(q.empty()) self.assertEqual("2", q.pop()) self.assertEqual("3", q.pop()) self.assertEqual("4", q.pop()) self.assertEqual("5", q.pop()) self.assertFalse(q.empty()) self.assertEqual("6", q.pop()) self.assertTrue(q.empty())
def setupAuxQueuesDictionary(): ''' Function to set up an OrderedDictionary that has 27 queues corresponding to ' ' and 26 alphabets added in correct order ''' auxQueueDictionary = OrderedDictionary(Queue()*27)
def __init__(self): self.__mediaQueue = Queue()
from myqueue import Queue myq = Queue() myq.Enqueue('A') myq.Enqueue('B') myq.Enqueue('C') myq.Enqueue('D') myq.Enqueue('E') myq.PrintQueue() print("Elements in queue: ", myq.queueNo) # Please check queue.py for details myq.Dequeue() myq.PrintQueue() print("Elements in queue: ", myq.queueNo) # Please check queue.py for details myq.Enqueue('F') myq.PrintQueue() print("Elements in queue: ", myq.queueNo) # Please check queue.py for details
class QueueTests(unittest.TestCase): def setUp(self): self.q = Queue() def test_len_returns_0_for_empty_queue(self): self.assertEqual(len(self.q), 0) def test_len_returns_correct_length_after_enqueue(self): self.assertEqual(len(self.q), 0) self.q.enqueue(2) self.assertEqual(len(self.q), 1) self.q.enqueue(4) self.assertEqual(len(self.q), 2) self.q.enqueue(6) self.q.enqueue(8) self.q.enqueue(10) self.q.enqueue(12) self.q.enqueue(14) self.q.enqueue(16) self.q.enqueue(18) self.assertEqual(len(self.q), 9) def test_empty_dequeue(self): self.assertIsNone(self.q.dequeue()) self.assertEqual(len(self.q), 0) def test_dequeue_respects_order(self): self.q.enqueue(100) self.q.enqueue(101) self.q.enqueue(105) self.assertEqual(self.q.dequeue(), 100) self.assertEqual(len(self.q), 2) self.assertEqual(self.q.dequeue(), 101) self.assertEqual(len(self.q), 1) self.assertEqual(self.q.dequeue(), 105) self.assertEqual(len(self.q), 0) self.assertIsNone(self.q.dequeue()) self.assertEqual(len(self.q), 0)
def setUp(self): self.q = Queue()
import os import requests import asyncio import websockets import json import parsing from myqueue import Queue EVENT_LOOP = asyncio.get_event_loop() HB_QUEUE = Queue() # qbtesting channel of the queuebottest Slack CHANNEL_ID = 'C77DZM4F9' def check_secrets_sourced(): """Errors out if Slack API key not found""" token = os.getenv('SLACK_BOT_TOKEN') if token: return token else: raise ValueError("No API token found! Have you sourced your secrets?") def connect(token): """Returns the WebSocket Message Server URL for this token's connection Connects to the Slack RTM API with the provided token and gets the WebSocket URL returned by the Slack API."""
def enqueue(self, item): Queue.enqueue(self, item) if self.function(item): Queue.enqueue(self, item)