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']
示例#2
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()
示例#3
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
示例#4
0
    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)
示例#5
0
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 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
示例#7
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 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
示例#9
0
    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
示例#10
0
	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 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')
示例#12
0
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 _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)
示例#14
0
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 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
示例#16
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
示例#17
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())