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 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 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 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 _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 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()
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
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 _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 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 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(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'
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 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 _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 __init__(self): """ Initialize class """ self.queue = Queue() self.start()
from myqueue import Queue queue1 = Queue() queue1.push("Ranjeet") print(queue1.pop()) print(queue1.pop())
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): self.__mediaQueue = Queue()
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 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 setupAuxQueuesDictionary(): ''' Function to set up an OrderedDictionary that has 27 queues corresponding to ' ' and 26 alphabets added in correct order ''' auxQueueDictionary = OrderedDictionary(Queue()*27)