当前位置: 首页>>代码示例>>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;未经允许,请勿转载。