當前位置: 首頁>>代碼示例>>Python>>正文


Python queue.PriorityQueue方法代碼示例

本文整理匯總了Python中queue.PriorityQueue方法的典型用法代碼示例。如果您正苦於以下問題:Python queue.PriorityQueue方法的具體用法?Python queue.PriorityQueue怎麽用?Python queue.PriorityQueue使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在queue的用法示例。


在下文中一共展示了queue.PriorityQueue方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: cull_it

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def cull_it(c):
    global CULL_RATE
    c_temp = PriorityQueue()
    qsize = c.qsize()
    l = int(qsize - qsize * CULL_RATE)
    result_out('[i]\tPopulation size %d, cull rate %s, living specimens: %d' % (c.qsize(), str(CULL_RATE), l))
    result_out('[.]\tBeginning the cull of underperforming creatures...')
    for i in range(l):
        flag = 0
        while flag == 0:
            tmp = c.get()
            if tmp[1].genome != '':
                c_temp.put(tmp)
                flag = 1
    result_out('[+]\tCull done!')
    return c_temp 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:18,代碼來源:jf-web.py

示例2: neighbor_search

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def neighbor_search(merit_func, old_vars, global_best, idx, max_depth, show_progress=True):
    nonconvex_vars = get_noncvx_vars(merit_func)
    for var in nonconvex_vars:
        var.value = var.z.value
    best_so_far = [merit_func.value, {v.id:v.value for v in merit_func.variables()}]

    eval_queue = PriorityQueue()
    add_neighbors(eval_queue, merit_func, best_so_far[1], old_vars, 1)
    count = 0
    while not eval_queue.empty():
        merit, _, node_depth, _, sltn = eval_queue.get()
        count += 1
        if merit < best_so_far[0]:# and merit < global_best[0]:
            if idx == 0 and show_progress:
                print(merit, count)
            best_so_far[0] = merit
            best_so_far[1] = sltn
            if node_depth < max_depth:
                add_neighbors(eval_queue, merit_func, sltn, old_vars, node_depth+1)

    return best_so_far 
開發者ID:cvxgrp,項目名稱:ncvx,代碼行數:23,代碼來源:admm_problem.py

示例3: dijkstra

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def dijkstra(self, from_vertex: int, to_vertex: int) -> None:
        vertices = [Vertex(i) for i in range(self._num_vertices)]
        vertices[from_vertex].distance_to_start = 0
        visited = [False] * self._num_vertices
        predecessor = [-1] * self._num_vertices
        q = PriorityQueue()
        q.put(vertices[from_vertex])
        visited[from_vertex] = True
        while not q.empty():
            min_vertex = q.get()
            if min_vertex.vertex_id == to_vertex:
                break
            for edge in self._adjacency[min_vertex.vertex_id]:
                next_vertex = vertices[edge.end_id]
                if min_vertex.distance_to_start + edge.weight < next_vertex.distance_to_start:
                    next_vertex.distance_to_start = min_vertex.distance_to_start + edge.weight
                    predecessor[next_vertex.vertex_id] = min_vertex.vertex_id
                    if not visited[next_vertex.vertex_id]:
                        q.put(next_vertex)
                        visited[next_vertex.vertex_id] = True
            
        path = lambda x: path(predecessor[x]) + [str(x)] if from_vertex != x else [str(from_vertex)]
        print("->".join(path(to_vertex))) 
開發者ID:wangzheng0822,項目名稱:algo,代碼行數:25,代碼來源:shortest_path.py

示例4: quantize

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def quantize(self):
        if self.h * self.w < self.maxColor:
            raise AttributeError("Image({0}x{1}) too small to be quantized".format(self.w, self.h))
        self.pixHisto = self.getPixHisto()

        orgVbox = self.createVbox(self.pixData)
        pOneQueue = PQueue(self.maxColor)
        pOneQueue.put((orgVbox.priority, orgVbox))
        popcolors = int(self.maxColor * self.fraction)

        pOneQueue = self.iterCut(popcolors, pOneQueue)

        boxQueue = PQueue(self.maxColor)
        while not pOneQueue.empty():
            vbox = pOneQueue.get()[1]
            vbox.priority *= vbox.vol
            boxQueue.put((vbox.priority, vbox))
        boxQueue = self.iterCut(self.maxColor - popcolors + 1, boxQueue, True)

        theme = []
        while not boxQueue.empty():
            theme.append(self.boxAvgColor(boxQueue.get()[1]))
        return theme 
開發者ID:rainyear,項目名稱:ImageColorTheme,代碼行數:25,代碼來源:MMCQ.py

示例5: __init__

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def __init__(self, agent_name: str, comm: CommunicationLayer, delay: float = None):
        self._queue = PriorityQueue()
        self._local_agent = agent_name
        self.discovery = comm.discovery
        self._comm = comm
        self._comm.messaging = self
        self._delay = delay
        self.logger = logging.getLogger(f"infrastructure.communication.{agent_name}")

        # Keep track of failer messages to retry later
        self._failed = []

        # Containers for metrics on sent messages:
        self.count_ext_msg = defaultdict(lambda: 0)  # type: Dict[str, int]
        self.size_ext_msg = defaultdict(lambda: 0)  # type: Dict[str, int]
        self.last_msg_time = 0
        self.msg_queue_count = 0

        self._shutdown = False 
開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:21,代碼來源:communication.py

示例6: huffman_hidden

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def huffman_hidden():  # builds the tree and returns root
    q = Queue.PriorityQueue()

    for key in freq:
        q.put((freq[key], key, Node(freq[key], key)))

    while q.qsize() != 1:
        a = q.get()
        b = q.get()
        obj = Node(a[0] + b[0], '\0')
        obj.left = a[2]
        obj.right = b[2]
        q.put((obj.freq, obj.data, obj))

    root = q.get()
    root = root[2]  # contains root object
    return root 
開發者ID:rootulp,項目名稱:hackerrank,代碼行數:19,代碼來源:tree-huffman-decoding.py

示例7: test_process_synchronize_sources_msg_db_error

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def test_process_synchronize_sources_msg_db_error(self, mock_process_message):
        """Test processing synchronize messages with database errors."""
        provider = Sources.objects.create(**self.aws_source)
        provider.save()
        future_mock = asyncio.Future()
        future_mock.set_result("test result")

        test_queue = queue.PriorityQueue()

        test_matrix = [
            {"test_value": {"operation": "update", "provider": provider}, "side_effect": InterfaceError},
            {"test_value": {"operation": "update", "provider": provider}, "side_effect": OperationalError},
        ]

        for i, test in enumerate(test_matrix):
            mock_process_message.side_effect = test.get("side_effect")
            with patch("sources.kafka_listener.connection.close") as close_mock:
                with patch.object(Config, "RETRY_SECONDS", 0):
                    process_synchronize_sources_msg((i, test["test_value"]), test_queue)
                    close_mock.assert_called()
        for i in range(2):
            priority, _ = test_queue.get_nowait()
            self.assertEqual(priority, i) 
開發者ID:project-koku,項目名稱:koku,代碼行數:25,代碼來源:test_kafka_listener.py

示例8: test_process_synchronize_sources_msg

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def test_process_synchronize_sources_msg(self, mock_process_message):
        """Test processing synchronize messages."""
        provider = Sources(**self.aws_source)

        test_queue = queue.PriorityQueue()

        messages = [
            {"operation": "create", "provider": provider, "offset": provider.offset},
            {"operation": "update", "provider": provider},
        ]

        for msg in messages:
            with patch("sources.storage.clear_update_flag") as mock_clear_flag:
                process_synchronize_sources_msg((0, msg), test_queue)
                mock_clear_flag.assert_called()

        msg = {"operation": "destroy", "provider": provider}
        with patch("sources.storage.clear_update_flag") as mock_clear_flag:
            process_synchronize_sources_msg((0, msg), test_queue)
            mock_clear_flag.assert_not_called() 
開發者ID:project-koku,項目名稱:koku,代碼行數:22,代碼來源:test_kafka_listener.py

示例9: mergeKLists

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def mergeKLists(self, lists) -> ListNode:
        # 使用優先隊列(堆排序)存儲每個list中的第一個節點,由優先隊列返回優先級最高(值最低的元素)
        head_pre = p = ListNode(0)
        prior_queue = PriorityQueue()
        for list_node in lists:
            if list_node:
                prior_queue.put((list_node.val, list_node))
        while not prior_queue.empty():
            node_val, node = prior_queue.get()
            p.next = ListNode(node_val)
            p = p.next
            # 將當前list的頭指向list中的下一個節點
            node = node.next
            if node:
                prior_queue.put((node.val, node))
        return head_pre.next 
開發者ID:asdf2014,項目名稱:algorithm,代碼行數:18,代碼來源:23_merge-k-sorted-lists.py

示例10: open_channel

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def open_channel(self, worker_id, assignment_id):
        """
        Opens a channel for a worker on a given assignment, doesn't re-open if the
        channel is already open.
        """
        connection_id = '{}_{}'.format(worker_id, assignment_id)
        if connection_id in self.queues and self.run[connection_id]:
            shared_utils.print_and_log(
                logging.DEBUG, 'Channel ({}) already open'.format(connection_id)
            )
            return
        self.run[connection_id] = True
        self.queues[connection_id] = PriorityQueue()
        self.last_sent_heartbeat_time[connection_id] = 0
        self.pongs_without_heartbeat[connection_id] = 0
        self.last_received_heartbeat[connection_id] = None
        self.worker_assign_ids[connection_id] = (worker_id, assignment_id) 
開發者ID:facebookresearch,項目名稱:ParlAI,代碼行數:19,代碼來源:socket_manager.py

示例11: __init__

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def __init__(self, host, port = 5551):
		self._sock = socket.create_connection((host, port), None)
		self._lock = threading.RLock()
		self._scanners = {}
		self._scan_wizards = {}
		self._connection_channels = {}
		self._get_info_response_queue = queue.Queue()
		self._get_button_uuid_queue = queue.Queue()
		self._timers = queue.PriorityQueue()
		self._handle_event_thread_ident = None
		self._closed = False
		
		self.on_new_verified_button = lambda bd_addr: None
		self.on_no_space_for_new_connection = lambda max_concurrently_connected_buttons: None
		self.on_got_space_for_new_connection = lambda max_concurrently_connected_buttons: None
		self.on_bluetooth_controller_state_change = lambda state: None 
開發者ID:BlackLight,項目名稱:platypush,代碼行數:18,代碼來源:fliclib.py

示例12: __init__

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def __init__(self, n, adj, cost):
        # See description of these parameters in the starter for
        # friend_suggestion
        self.n = n
        self.INFINITY = n * maxlen
        self.adj = adj
        self.cost = cost
        self.bidistance = [[self.INFINITY] * n, [self.INFINITY] * n]
        self.visited = [False] * n
        self.visited = []
        self.q = queue.PriorityQueue()
        # Levels of nodes for node ordering heuristics
        self.level = [0] * n
        # Positions of nodes in the node ordering
        self.rank = [0] * n

        # Implement preprocessing here
        pass 
開發者ID:huyvohcmc,項目名稱:coursera-dsa,代碼行數:20,代碼來源:travelling_salesman_problem.py

示例13: __init__

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def __init__(self):
        self.todo_queue = queue.PriorityQueue()
        self.done_queues = {}
        self.done_tasks_time = dict()
        self.done_tasks_time_max = (60.0 * 20)
        self.broadcast_todo_queue = {}
        self.start_calc = {}
        self.out_tasks = {}
        self.proj_alive_time = {}
        self.proj_alive_time_max = (60 * 5)
        self.worker_alive_time = {}
        self.worker_alive_time_max = (60 * 30)
        self.pub_logger = logging.getLogger()
        self.pub_logger.setLevel(logging.WARN)
        if False:
            h = logging.handlers.RotatingFileHandler(filename='./server.log', mode='a', maxBytes=1000000, backupCount=10)
        else:
            h = logging.handlers.RotatingFileHandler(filename='./server.log', mode='a')
        f = logging.Formatter('%(asctime)s %(host)-16s %(job_id)-16s %(source_type)-8s %(levelname)-8s %(message)s')
        h.setFormatter(f)
        self.pub_logger.addHandler(h)
        self.logger = logging.LoggerAdapter(logging.getLogger(), {'host': os.environ.get('HOSTNAME', 'unknown'), 'job_id': os.environ.get('PBS_JOBID', 'N/A').split('.')[0], 'source_type': 'queue_server', })
        self.process = psutil.Process(os.getpid())
        _thread.start_new_thread(QueueServer.remove_dead_projects_daemon, (self,)) 
開發者ID:xulabs,項目名稱:aitom,代碼行數:26,代碼來源:queue_server.py

示例14: dijkstra

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def dijkstra(dist, graph, src):
    que = PriorityQueue()
    que.put(edge(0, src))
    while not que.empty():
        p = que.get()
        v = p.to
        if dist[src][v] < p.cost:
            continue
        for i in range(len(graph[v])):
            if dist[src][graph[v][i].to] > dist[src][v] + graph[v][i].cost:
                dist[src][graph[v][i].to] = dist[src][v] + graph[v][i].cost
                que.put(edge(dist[src][graph[v][i].to], graph[v][i].to))


# @param{dist:距離矩陣,dims:降維的維度}
# return:降維後的矩陣 
開發者ID:tracy-talent,項目名稱:curriculum,代碼行數:18,代碼來源:ISOMAP.py

示例15: _process_nonrealtime_stop

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import PriorityQueue [as 別名]
def _process_nonrealtime_stop(self, state):
        import supriya.patterns

        if not state["has_stopped"]:
            state["has_stopped"] = True
        self._debug("UNWINDING")
        assert state["event_queue"].qsize() == 1

        event_tuple = state["event_queue"].get()
        if event_tuple.iterator_index not in state["visited_iterators"]:
            self._debug("    DISCARDING, UNVISITED", event_tuple)
        elif not isinstance(event_tuple.event, supriya.patterns.CompositeEvent):
            self._debug("    DISCARDING, NON-COMPOSITE", event_tuple)
        elif not event_tuple.event.get("is_stop"):
            self._debug("    DISCARDING, NON-STOP", event_tuple)
        else:
            self._debug("    PRESERVING", event_tuple)
            state["event_queue"].put(event_tuple._replace(offset=0.0))

        iterator_queue = PriorityQueue()
        while not state["iterator_queue"].empty():
            iterator_tuple = state["iterator_queue"].get()
            iterator_tuple = iterator_tuple._replace(offset=0.0)
            iterator_queue.put(iterator_tuple)
        state["iterator_queue"] = iterator_queue 
開發者ID:josiah-wolf-oberholtzer,項目名稱:supriya,代碼行數:27,代碼來源:Ppar.py


注:本文中的queue.PriorityQueue方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。