Exemplo n.º 1
0
 def test_queues(self):
     q = Queue()
     for i in range(1,100):
         q.push(i)
     self.assertEqual(99,q.size())
     self.assertEqual(1,q.peek())
     self.assertEqual(1,q.pop())
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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())
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
 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 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)
Exemplo n.º 8
0
def simulation(numSeconds, pagesPerMinute):

    labprinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingtimes = []

    for currentSecond in range(numSeconds):

      if newPrintTask():
         task = Task(currentSecond)
         printQueue.enQueue(task)

      if (not labprinter.busy()) and (not printQueue.isEmpty()):
        nexttask = printQueue.deQueue()
        waitingtimes.append( nexttask.waitTime(currentSecond))
        labprinter.startNext(nexttask)

      labprinter.tick()
 
    averageWait=sum(waitingtimes)/len(waitingtimes)
    print("Average Wait %6.2f secs %3d tasks remaining."%(averageWait,printQueue.size()))
Exemplo n.º 9
0
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
Exemplo n.º 10
0
 def test_size(self):
     q = Queue()
     assert q.size() == 0
     q.enqueue('Python')
     q.enqueue('Java')
     assert q.size() == 2