def Algorithm1(G, basesore, sourceList): n = 0 SG = nx.MultiGraph() simqueue = Queue() for i in range(len(sourceList)): simqueue.enqueue(sourceList[i]) # while(not(simqueue.empty())): while (n < 100 and simqueue.size() < 98): # print ("这次感染队列列表有个感染点") # print (simqueue.size()) sourceItem_ = simqueue.dequeue() SG.add_node(sourceItem_) for sourceNeightor in list(G.neighbors(sourceItem_)): if G.node[sourceNeightor]['Cn'] == 0: G.node[sourceNeightor]['Scn'] += G.nodes[sourceItem_]['Scn'] G.add_node(sourceNeightor, Cn=1) SG.add_node(sourceNeightor) SG.add_edge(sourceItem_, sourceNeightor) simqueue.enqueue(sourceNeightor) n += 1 #对所有n<V(就是分数达到阕值的节点感染)算是谣言的不同之处吧。更新。 for index in range(1, 35): if G.node[index]['Scn'] > basesore: G.add_node(index, Cn=1) return G, SG
def test(): from random import randint students = 10 taskPerStuUpTo = 2 pagesUpTo = 20 printPeriod = 1 * 60 * 60 aPrintQueue = Queue() aPrinter = Printer(speed = 12, printQueue = aPrintQueue, printPeriod = 3600) numOfTasks = 0 for i in range(students): numOfTasks += randint(0, taskPerStuUpTo) enterTimeList = [] for i in range(numOfTasks): enterTimeList.append(randint(0, printPeriod -1)) enterTimeList.sort() lastEndTime = 0 for enterTime in enterTimeList: aTask = Task(enterTime, randint(1,pagesUpTo), lastEndTime, aPrinter.speed) aPrintQueue.enqueue(aTask) lastEndTime = aTask.endTime() ## print(aPrintQueue.size()) totalWaitTime = 0 ## print(aPrinter.printQueue.size()) ## print('isEmpty',aPrinter.printQueue.isEmpty()) ## print(aPrinter.isBusy()) while aPrinter.isBusy(): ## print(aPrinter.isBusy()) ## print(totalWaitTime) totalWaitTime += aPrinter.printQueue.dequeue().taskLastTime() return totalWaitTime / numOfTasks
def test_enqueue(self): q = Queue() q.enqueue('Python') assert list(q.items) == ['Python'] # Add another item q.enqueue('Java') assert list(q.items) == ['Python', 'Java']
def testWaitTime(numOfStudents, duration): numOfTasks = numOfStudents * 2 ## print(numOfTasks) printQueue = Queue() aPrinter = Printer(10) waitTimeList = [] for currentSecond in range(duration): if hasTask(numOfTasks, duration): timeStamp = currentSecond ## print(timeStamp) printQueue.enqueue(Task(timeStamp)) if not aPrinter.isBusy() and not printQueue.isEmpty(): currentTask = printQueue.dequeue() aPrinter.nextTask(currentTask) waitTimeList.append(currentSecond - currentTask.timeStamp) ## print('currentSecond', currentSecond) ## print('currentTask.timeStamp', currentTask.timeStamp) ## print('currentSecond - currentTask.timeStamp', currentSecond - currentTask.timeStamp) aPrinter.timeRemain = 60 / aPrinter.ppm * currentTask.pages ## print(aPrinter.ppm) ## print('pages: {}, timeRemain: {}'.format(currentTask.pages,aPrinter.timeRemain)) if aPrinter.isBusy(): ## print(currentSecond) aPrinter.tick() if aPrinter.timeRemain <= 0: aPrinter.currentTask = None return sum(waitTimeList) / len(waitTimeList)
def stronglyConnectedComponents(g): """return the Strongly Connected Components of a DFSGraph g""" g.dfs() transG = DFSGraph() g.transpose(transG) transG.dfsFinishDecreasingOrder() # dict of path per vertex pathDict = {} for vert in transG: pathDict[vert.getId()] = transG.traverse(vert) print( pathDict) sccList = [] seen = set() q = Queue() vertices = [vert for vert in transG] vertices.sort(key=lambda vert: vert.getFinish()) vertices.reverse() for vert in vertices: print(vert.getId()) if vert in seen: continue q.enqueue(vert) scc = set() while (not q.isEmpty()): x = q.dequeue() seen.add(x) scc.add(x.getId()) for v in x.getConnections(): if v.getPred() == x: q.enqueue(v) sccList.append(scc) return sccList
def test_dequeue(self): q = Queue() q.dequeue() q.enqueue('Python') q.enqueue('Java') result = q.dequeue() assert result == 'Python' assert list(q.items) == ['Java']
class TestQueues(unittest.TestCase): def setUp(self): self.Q = Queue(N=5) def test_setup(self): "Test for Empty Queue" self.assertEqual(self.Q.size(), 0) self.assertTrue(self.Q.isEmpty()) self.assertFalse(self.Q.isFull()) with self.assertRaises(EmptyQueueException) as cm: self.Q.dequeue() expected_msg = "Queue is empty" self.assertEquals(cm.exception.message, expected_msg) with self.assertRaises(EmptyQueueException) as cm: self.Q.front() expected_msg = "Queue is empty" self.assertEquals(cm.exception.message, expected_msg) def test_enqueue_dequeue(self): self.Q.enqueue('A') self.Q.enqueue('B') self.assertEqual(self.Q.size(), 2) self.assertFalse(self.Q.isEmpty()) self.assertFalse(self.Q.isFull()) self.Q.enqueue('C') self.Q.enqueue('D') self.Q.enqueue('E') self.assertFalse(self.Q.isEmpty()) self.assertTrue(self.Q.isFull()) self.assertEqual(self.Q.front(), 'A') with self.assertRaises(FullQueueException) as cm: self.Q.enqueue('F') expected_msg = "Queue is full" self.assertEquals(cm.exception.message, expected_msg) self.assertEqual(self.Q.size(), 5) self.Q.dequeue() self.assertEqual(self.Q.size(), 4) self.assertFalse(self.Q.isEmpty()) self.assertFalse(self.Q.isFull()) self.Q.enqueue('G') self.assertEqual(self.Q.front(), 'B') self.assertEqual(self.Q.size(), 5) self.Q.dequeue() self.Q.dequeue() self.Q.dequeue() self.Q.dequeue() self.assertEqual(self.Q.size(), 1) self.assertEqual(self.Q.front(), 'G') self.assertFalse(self.Q.isEmpty()) self.assertFalse(self.Q.isFull()) self.Q.dequeue() self.assertEqual(self.Q.size(), 0) with self.assertRaises(EmptyQueueException) as cm: self.Q.dequeue() expected_msg = "Queue is empty" self.assertEquals(cm.exception.message, expected_msg) self.assertTrue(self.Q.isEmpty()) self.assertFalse(self.Q.isFull())
def levelOrder(self): if self.size > 0: queue = Queue() queue.enqueue(self.root) while not queue.isEmpty(): print(queue.front().data) queue.dequeue() pass pass
def josephus(nameList, count): q = Queue() for name in nameList: q.enqueue(name) while q.size() > 1: for j in range(count + 1): out = q.dequeue() if j != count: q.enqueue(out) return q.dequeue()
def breadth_first_search(self, starting_vert): to_visit = Queue() visited = set() to_visit.enqueue(starting_vert) visited.add(starting_vert) while to_visit.size() > 0: current_vert = to_visit.dequeue() for next_vert in current_vert.get_connections(): if next_vert not in visited: visited.add(next_vert) to_visit.enqueue(next_vert)
def queues(): queue = Queue() queue.enqueue(4) queue.enqueue(40) queue.enqueue(5) queue.enqueue(3) queue.enqueue(7) print(queue)
class BinaryTree: root = None # size : keeps track of no. of nodes and nothing else size = None queue = None def __init__(self): self.size = 0 self.queue = Queue() def add(self, data): node = Node(data) # self.queue.enqueue(node) if self.root is None: self.root = node self.size += 1 self.queue.enqueue(self.root) elif not self.queue.isEmpty(): front = self.queue.front() if front.lchild is None: front.lchild = node else: front.rchild = node self.queue.dequeue() self.queue.enqueue(node) self.size += 1 def preOrder(self): def r(node): if node is None: return print(node.data) r(node.lchild) r(node.rchild) pass r(self.root) def levelOrder(self): if self.size > 0: queue = Queue() queue.enqueue(self.root) while not queue.isEmpty(): print(queue.front().data) queue.dequeue() pass pass
def are_connected(self, person1, person2): queue = Queue() seen = set() queue.enqueue(person1) while not queue.is_empty(): current = queue.dequeue() seen.add(current) print("current:", current) print("seen:", seen) if current is person2: return True for adjacent in current.adjacent: queue.enqueue(adjacent) return False
def detect(self): """Detect Boundary """ self.get_diff_queue() self.threshold = adaptive_threshold.calc_threshold( self.diff_queue, constants.THRESHOLD_CONST) boundary_queue = Queue() for diff in self.diff_queue.get(): if(diff['value'] >= self.threshold): print("Shot Boundary Detected : {} - {}" . format(diff['prev_frame'], diff['next_frame'])) boundary_queue.enqueue(diff) list_index = self.get_list_keyframes_index(boundary_queue) self.save_keyframes(list_index) self.save_shots(boundary_queue) return list_index
def bfs(g,start): """Breadth First Search from start vertex""" start.setDistance(0) start.setPred(None) # start at the front of the queue vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): # explore vertices at the front of the queue currentVert = vertQueue.dequeue() # all adjacent vertices of currentVert 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 _findPathInResidualNetwork(self, s, t, path=[]): """find a path as list from s to t in residual network based on Breadth First Search""" self._initializeColorDistanceParent(s) queue = Queue() queue.enqueue(s) while (queue.size() > 0): u = queue.dequeue() for edge in self.adj[u]: v = edge.getDestination() if self.color[v] == WHITE: residualCapacity = edge.getCapacity() - self.flow[edge.getEndPoints()] if residualCapacity > 0: self.color[v] = GREY self.distance[v] = self.distance[u] + 1 self.parentEdge[v] = (edge, residualCapacity) queue.enqueue(v) self.color[u] = BLACK # build improving path return self._buildImprovingPath(s,t)
class Table: """The table where the Players of the two Teams are sitting, controlling the Players turns.""" def __init__(self, team1, team2, player_playing_first): self.players = [ team1.player1, team2.player1, team1.player2, team2.player2 ] # Init seats self.seats = Queue() for p in self.players: self.seats.enqueue(p) # Set player who plays first next while not self.seats.peek() == player_playing_first: self.get_next_player() def get_next_player(self): """Returns the player who plays next.""" player = self.seats.dequeue() self.seats.enqueue(player) return player def __str__(self): p1 = f'{self.players[0]}' p2 = f'{self.players[1]}' p3 = f'{self.players[2]}' p4 = f'{self.players[3]}' if p1 == self.seats.peek(): p1 = f'*{p1}*' elif p2 == self.seats.peek(): p2 = f'*{p2}*' elif p3 == self.seats.peek(): p3 = f'*{p3}*' else: p4 = f'*{p4}*' return f'-- Table --\n\n\t\t\t{p1}\n\n\n\t{p2}\t\t\t{p4}\n\n\n\t\t\t{p3}'
def simulate_test(): """ Simulate behavior of one client Returns ------- current_time : int How many se """ #Creating queues, a client, and enqueueing the client print('Utworzono kolejki!') q1 = Queue(queue_type=1) q2 = Queue(queue_type=2) q3 = Queue(queue_type=3) print('Utworzono klienta!') c1 = Client(1) print('Dołączam do kolejki') q1.enqueue(c1) # max time equals 9 hours max_time = 9 * 3600 # time spent on registering current_time = c1.register_time while current_time < max_time: if current_time + c1.selection_time + 1800 > max_time: print("I won't manage to play another game, quitting...") c1.set_type(3) # find best queue q3.enqueue(c1) # wait for your turn current_time += c1.signoff_time q3.dequeue() break selection_time = c1.selection_time print("I've chosen a game in {}!".format(manage_time(selection_time))) game_time = int(np.random.normal(1800, 900)) print("I played for {}!".format(manage_time(game_time))) current_time += selection_time + game_time print("Ending within {}".format(manage_time(current_time))) return current_time
def insertInBinaryTreeUsingLevelOrder(root, data): newNode = BinaryTree(data) if root is None: root = newNode return root q = Queue() q.enqueue(root) node = None while not q.isEmpty(): node = q.dequeue() # dequeue FIFO if data == node.get_data(): return root # basically level order, insert would be where there is no left if node.left is not None: q.enqueue(node.left) else: node.left = newNode return root # if left all filled, insert right if node.right is not None: q.enqueue(node.right) else: node.right = newNode return root
def detect(self, algorithm=2, threshold=1, method=1): """Detect Boundary """ self.get_diff_queue(method) self.threshold = adaptive_threshold.calc_threshold( self.diff_queue, threshold) boundary_queue = Queue() end = { 'prev_frame': self.diff_queue.size() - 1, 'next_frame': self.diff_queue.size() - 1, 'value': 0 } boundary_queue.enqueue(end) for diff in self.diff_queue.get(): # print("{}".format(diff['value'])) if (diff['value'] >= self.threshold): print("Shot Boundary Detected : {} - {}".format( diff['prev_frame'], diff['next_frame'])) boundary_queue.enqueue(diff) start = {'prev_frame': 0, 'next_frame': 0, 'value': 0} boundary_queue.enqueue(start) list_index = self.get_list_keyframes_index(boundary_queue, algorithm) list_shots = self.get_list_shots(boundary_queue) diffs = self.diff_queue.get() diffs.reverse() self.delete_dir_content(constants.IMAGES_DIR) self.delete_dir_content(constants.SHOTS_DIR) self.save_keyframes(list_index) self.save_shots(list_shots) return list_index, diffs, self.threshold
class StackUsingQueue: ''' Implementing Stack using two queues We implement only push and pop methods ''' def __init__(self): self.a_queue = Queue(20) self.b_queue = Queue(20) def push(self, x): self.a_queue.enqueue(x) print("Pushed element: {}\n".format(x)) print("A Queue: ", end="") self.a_queue.print() print("B Queue: ", end="") self.b_queue.print() print("---------------------------------------------") def pop(self): # dequeue all except one element from A and enqueue to B while True: x = self.a_queue.dequeue() self.b_queue.enqueue(x) if (self.a_queue.head + 1 == self.a_queue.tail) or \ (self.a_queue.head == self.a_queue.MAXSIZE and self.a_queue.tail == 0): break element = self.a_queue.dequeue() # swap queues A and B self.a_queue, self.b_queue = self.b_queue, self.a_queue print("Popped element: {}\n".format(element)) print("A Queue: ", end="") self.a_queue.print() print("B Queue: ", end="") self.b_queue.print() print("---------------------------------------------") return element
def waitTime(numStudents=10, pagePerMin=10): from random import randint from queues import Queue numOfPrints = 0 #each student prints 1-2 times for student in range(numStudents): numOfPrints += randint(0,2) ## print(numOfPrints) pageList = [] #1-20 pages per print for i in range(numOfPrints): pageList.append(randint(1, 20)) ## print(pageList) timePerPage = 1 * 60 / pagePerMin enterTimeList = [] #3600 seconds in an hour, make a random list of time each print enters for i in range(numOfPrints): enterTimeList.append(randint(0,3599)) enterTimeList.sort() ## print(enterTimeList) listToQueue = zip(enterTimeList, pageList) printQueue = Queue() for item in listToQueue: printQueue.enqueue(item) lastEndTime = 0 totalWaitTime = 0 while printQueue.size(): aPrint = printQueue.dequeue() thisEnterTime = aPrint[0] thisPrintDur = aPrint[1] * timePerPage endStartDiff = lastEndTime - thisEnterTime endStartDiff = endStartDiff if endStartDiff > 0 else 0 thisStartTime = thisEnterTime + endStartDiff thisEndTime = thisStartTime + thisPrintDur totalWaitTime += (thisEndTime - thisEnterTime) lastEndTime = thisEndTime ## print('thisEnterTime: {}, thisPrintDur: {}, endStartDiff: {}, thisStartTime: {}, thisEndTime: {}, totalWaitTime: {}'.format(thisEnterTime, thisPrintDur, endStartDiff, thisStartTime, thisEndTime, totalWaitTime)) return totalWaitTime / numOfPrints
def make_queue(): queue = Queue() queue.enqueue(23) queue.enqueue(45) queue.enqueue(58) queue.enqueue(34) queue.enqueue(45) print(f"Queue: {queue.items}")
def sumInBinaryTreeLevelOrder(root): if root is None: return 0 q = Queue() q.enqueue(root) node = None sum = 0 while not q.isEmpty(): node = q.dequeue() # dequeue FIFO sum += node.get_data() if node.left is not None: q.enqueue(node.left) if node.right is not None: q.enqueue(node.right) return sum
def levelOrderTraversal(self,result): rootNode = self.root q = Queue() q.enqueue(rootNode) node = None while not q.isEmpty(): node = q.dequeue() result.append(node.val) if node.left_child != None: q.enqueue(node.left_child) if node.right_child != None: q.enqueue(node.right_child) return result
def levelOrder(root, result): if root is None: return q = Queue() q.enqueue(root) n = None while not q.isEmpty(): n = q.dequeue() # dequeue FIFO result.append(n.get_data()) if n.left is not None: q.enqueue(n.left) if n.right is not None: q.enqueue(n.right) return result
def findSizeusingLevelOrder(root): if root is None: return 0 q = Queue() q.enqueue(root) node = None count = 0 while not q.isEmpty(): node = q.dequeue() # dequeue FIFO count += 1 if node.left is not None: q.enqueue(node.left) if node.right is not None: q.enqueue(node.right) return count
def bft_print(self): if self: queue = Queue() current_node = self queue.enqueue(current_node) # while the queue isn't empty # take out the first on the list and make it the current node then print it # If the current node has a left and a right, add it to the while len(queue) != 0: current_node = queue.dequeue() print(current_node.value) if current_node.left: queue.enqueue(current_node.left) if current_node.right: queue.enqueue(current_node.right)
def numberOfLeavesInBTusingLevelOrder(root): if root is None: return 0 q = Queue() q.enqueue(root) node = None count = 0 while not q.isEmpty(): node = q.dequeue() # dequeue FIFO # leaves has no left and right so increment here # can also find number of full nodes with not None here if node.left is None and node.right is None: count += 1 else: if node.left is not None: q.enqueue(node.left) if node.right is not None: q.enqueue(node.right) return count
def bft_print(self, node): # You should import the queue class from earlier in the # week and use that class to implement this method # Use a queue to form a "line" # for the nodes to "get in" queue = Queue() queue.enqueue(self) # need a while loop to iterate # what are we checking in the while statement? # while length of queue is greater than 0 while len(queue) > 0: # dequeue item from front of queue val = queue.dequeue() # print that item print(val.value) # place current item's left node in queue if not None if val.left: queue.enqueue(val.left) # place current item's right node in queue if not None if val.right: queue.enqueue(val.right)
# queue - 11,17,12,18,13,19,14,20,15,21,16,22 while not stk.isEmpty(): que.enqueue(stk.pop()) que.enqueue(que.dequeue()) if __name__ == "__main__": # basically get the stack to a place where you can pop for first part of interleave # and remainder of queue you can dequeue to the end for second part of interleave # time: O(n) # space: O(n) que = Queue(20) que.enqueue(11) que.enqueue(12) que.enqueue(13) que.enqueue(14) que.enqueue(15) que.enqueue(16) que.enqueue(17) que.enqueue(18) que.enqueue(19) que.enqueue(20) que.enqueue(21) que.enqueue(22) interLeavingQueue(que) while not que.isEmpty():
from queues import Queue queue = Queue() queue.enqueue(2) queue.enqueue(3) queue.enqueue(5) queue.enqueue(9) print(queue.to_string()) print(queue.dequeue()) print(queue.to_string())
def test_isEmpty(self): q = Queue() assert q.isEmpty() == True q.enqueue('Python') assert q.isEmpty() == False
def test_size(self): q = Queue() assert q.size() == 0 q.enqueue('Python') q.enqueue('Java') assert q.size() == 2