Пример #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
Пример #2
0
    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
Пример #3
0
    def __init__(self):
        # once pressed, and released; keys show up in this queue
        self._changes = Queue(24)
        self.key_pressed = ''

        self.debug = 0  # 0..2

        self.last_event_time = utime.ticks_ms()
Пример #4
0
def queues():
    queue = Queue()
    queue.enqueue(4)
    queue.enqueue(40)
    queue.enqueue(5)
    queue.enqueue(3)
    queue.enqueue(7)
    print(queue)
Пример #5
0
def broadTravel(t):
    q=Queue()
    q.put(t)
    while q.qsize()>0:
        tmp=q.get()
        print tmp.value
        if tmp.left is not None:
            q.put(tmp.left)
        if tmp.right is not None:
            q.put(tmp.right)
Пример #6
0
 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']
Пример #7
0
    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()
Пример #8
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()
Пример #9
0
def bfs(start, end):
    """
    Breadth first search. Takes a start tile and end tile, and uses
    their neighbour list to traverse.
    Uses the LIFO queue in queues.py.
    :param start: Tile
    :param end: Tile
    :return: came_from, dictionary with all tiles, and where we came from (parent).
             success, True or False. If the algorithm found the end tile or not.
             has_been_next, list over tiles that has been considered as the next tile.
    """
    frontier = Queue()
    frontier.add(start)
    came_from = {start: None}
    success = False
    has_been_next = []

    while not frontier.empty():
        current = frontier.pop()
        current.visit()
        if current == end:
            print("Breadth First Search, successful.")
            success = True
            break

        for next_tile in current.neighbours:
            if next_tile not in has_been_next:
                has_been_next.append(next_tile)
            if next_tile not in came_from:
                frontier.add(next_tile)
                came_from[next_tile] = current

    return came_from, success, has_been_next
Пример #10
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
Пример #11
0
class RPN_converter:
    """convert a list of numbers and operations and functions to RPN format"""
    def __init__(self):
        self.operators = Stack()
        self.output = Queue()
        self.out = []

    def convert(self, elements):
        """convert given list to RPN format"""
        for element in elements:
            if isinstance(element, (float, int)):
                self.output.push(element)
            elif isinstance(element, Function):
                self.operators.push(element)
            elif element == "(":
                self.operators.push(element)
            elif element == ")":
                while self.operators.peek() != "(":
                    self.output.push(self.operators.pop())
                self.operators.pop()
            elif isinstance(element, Operator):
                while self.operators.peek() != None or self.operators.peek(
                ) != "(":
                    if isinstance(self.operators.peek(), Operator) and \
                    self.operators.peek() > element:
                        self.output.push(self.operators.pop())
                    else:
                        break
                self.operators.push(element)

        while self.operators.peek() != None:
            self.output.push(self.operators.pop())

        return self.output.items
Пример #12
0
    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
Пример #13
0
def bfs(start_tile, end_tile):
    """
    Breadth-first search algorithm
    :param start_tile: Tile object, start tile of board
    :param end_tile: Tile object, end tile of board
    :return:
    """
    queue = Queue()
    queue.put(start_tile)
    came_from = {}
    came_from[start_tile] = None
    has_been_next_tile = []

    while not queue.empty():
        current_tile = queue.get()
        current_tile.visit()

        if current_tile == end_tile:
            break

        for next_tile in current_tile.neighbours:

            if next_tile not in has_been_next_tile:
                has_been_next_tile.append(next_tile)

            if next_tile not in came_from:
                queue.put(next_tile)
                came_from[next_tile] = current_tile
                current_tile.visit()

    return came_from, has_been_next_tile
    def __init__(self, dataStructure):
        super(interactiveDataStructures, self).__init__()
        # rich module elements
        pretty.install()
        traceback.install()
        self.console = Console()
        # Datastructure elements
        availableDataStrutuces = {
            'DynamicArray': DynamicArray(),
            'SingleLinkedList': SinglyLinkedList(),
            'DoublyLinkedList': DoublyLinkedList(),
            'Stack': Stack(),
            'Queue': Queue(),
            'PriorityQueue': PriorityQueue()
            }

        correspondingNodes = {
            'DynamicArray': None,
            'SingleLinkedList': ListNode(None),
            'DoublyLinkedList': ListNode(None),
            'Stack': StackNode(None),
            'Queue': QueueNode(None),
            'PriorityQueue': PQNode(None)
            }

        if dataStructure in availableDataStrutuces:
            self.dataStructure = availableDataStrutuces[dataStructure]
            self.DSNode = correspondingNodes[dataStructure]
            self.DSname = dataStructure
            interactiveDataStructures.prompt = text.Text(f'({dataStructure}) ', style="bold magenta") # doesn't quite work
        else:
            raise ValueError(f'Please choose one of the following available data structure: {availableDataStrutuces.keys()}')
Пример #15
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
Пример #16
0
async def consume(config):
    queue = Queue(id=config.q)
    loop = asyncio.get_running_loop()

    await init_redis(loop)
    while True:
        await consume_queue(queue)
Пример #17
0
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}")
Пример #18
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
Пример #19
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
Пример #20
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())
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
Пример #22
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
Пример #23
0
    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
Пример #24
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
Пример #25
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)
Пример #26
0
async def test_consumer_integration(redis):
    async def task():
        return 1

    queue = Queue(id='test_queue')
    job = Job(queue_id=queue.id, task=task)
    await EnqueueJobUseCase(job).execute()

    result = await ConsumeQueue(queue).execute()

    assert result == 1
Пример #27
0
 def test_length(self):
     q = Queue()
     assert q.length() == 0
     q.enqueue('A')
     assert q.length() == 1
     q.enqueue('B')
     assert q.length() == 2
     q.dequeue()
     assert q.length() == 1
     q.dequeue()
     assert q.length() == 0
Пример #28
0
 def test_front(self):
     q = Queue()
     assert q.front() is None
     q.enqueue('A')
     assert q.front() == 'A'
     q.enqueue('B')
     assert q.front() == 'A'
     q.dequeue()
     assert q.front() == 'B'
     q.dequeue()
     assert q.front() is None
Пример #29
0
 def test_dequeue(self):
     q = Queue(['A', 'B', 'C'])
     assert q.dequeue() == 'A'
     assert q.length() == 2
     assert q.dequeue() == 'B'
     assert q.length() == 1
     assert q.dequeue() == 'C'
     assert q.length() == 0
     assert q.is_empty() is True
     with self.assertRaises(ValueError):
         q.dequeue()
Пример #30
0
 def test_enqueue(self):
     q = Queue()
     q.enqueue('A')
     assert q.front() == 'A'
     assert q.length() == 1
     q.enqueue('B')
     assert q.front() == 'A'
     assert q.length() == 2
     q.enqueue('C')
     assert q.front() == 'A'
     assert q.length() == 3
     assert q.is_empty() is False
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
Пример #32
0
 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 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)
Пример #35
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()))
Пример #36
0
def test_Queue( size ):

  # Create the queue
  queue = Queue( size )

  # Fill up the queue
  for i in range( size ):
    queue.enq( i )
    assert queue.peek()     == 0
    assert queue.is_empty() == False

  # Check the queue is full
  assert queue.is_full()

  # Check enqueuing throws an assert
  with pytest.raises( AssertionError ):
    queue.enq( 0 )

  # Empty the queue, check the order is correct
  for i in range( size ):
    assert queue.deq()     == i
    assert queue.is_full() == False

  # Check the queue is empty
  assert queue.is_empty()

  # Check that dequeuing throws an assert
  with pytest.raises( IndexError ):
    queue.deq()