Exemplo n.º 1
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
Exemplo n.º 2
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)
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
Exemplo n.º 4
0
    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
Exemplo n.º 5
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.º 6
0
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
Exemplo n.º 7
0
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
Exemplo n.º 8
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
Exemplo n.º 9
0
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
Exemplo n.º 10
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
Exemplo n.º 11
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()))
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
Exemplo n.º 13
0
        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():
        print(que.dequeue())
Exemplo n.º 14
0
 def test_isEmpty(self):
     q = Queue()
     assert q.isEmpty() == True
     q.enqueue('Python')
     assert q.isEmpty() == False