亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用于在 Python 中構建 PriorityQueue 的自定義比較器

用于在 Python 中構建 PriorityQueue 的自定義比較器

米琪卡哇伊 2022-05-24 18:19:24
我正在嘗試在 Python 中使用 PriorityQueue 構建優先級隊列,但不是要考慮進行優先級比較的元素,而是希望它在將元素傳遞給函數后使用函數的返回值,類似于 sorted(mtlist,key = myfun),有沒有辦法做到這一點,
查看完整描述

3 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

與其將元素直接插入隊列,不如將每個元素包裝在一個元組中,其中元組中的第一個元素是所需的排序鍵。元組按其元素的順序排序(即,首先比較第一個元素),因此排序鍵需要排在第一位。


import heapq


queue = []

my_list = [...]

for element in my_list:

    heapq.heappush(queue, (my_func(element), element))


查看完整回答
反對 回復 2022-05-24
?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

如果您有元素的包裝類,那么您可以使用運算符重載。


例如,假設您有一個CustomNumber類(相當于您的元素),其中順序由模 16 值(私有函數__f())確定,您可以覆蓋比較運算符,例如:


class CustomNumber:

    def __init__(self, value):

        self.value = value


    def __f(self, x):

        return x % 16


    def __lt__(self, obj):

        """self < obj."""

        return self.__f(self.value) < self.__f(obj.value)


    def __le__(self, obj):

        """self <= obj."""

        return self.__f(self.value) <= self.__f(obj.value)


    def __eq__(self, obj):

        """self == obj."""

        return self.__f(self.value) == self.__f(obj.value)


    def __ne__(self, obj):

        """self != obj."""

        return self.__f(self.value) != self.__f(obj.value)


    def __gt__(self, obj):

        """self > obj."""

        return self.__f(self.value) > self.__f(obj.value)


    def __ge__(self, obj):

        """self >= obj."""

        return self.__f(self.value) >= self.__f(obj.value)

這樣下面的代碼:


a = CustomNumber(16)

b = CustomNumber(14)


print('a < b =', a < b)

print('a <= b =', a <= b)

print('a == b =', a == b)

print('a != b =', a != b)

print('a > b =', a > b)

print('a >= b =', a >= b)

印刷:


a < b = True

a <= b = True

a == b = False

a != b = True

a > b = False

a >= b = False


查看完整回答
反對 回復 2022-05-24
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

Here is an example of using custom sort in PriorityQueue in Python.


We use a priority-queue (heapq) find the next element to add. To make the

implementation simple we "monkey patch" the ListNode class to have a custom

 less-than function using setattr. Note that, simply using the tuple trick 

 and pushing (node.val, node) to the priority queue will not work because 

 the lists have values in common.


class Solution:

    def mergeKLists(self, lists: List[ListNode]) -> ListNode:

    

    setattr(ListNode, "__lt__", lambda self, other: self.val <= other.val)

        

    pq = []

    for l in lists:

        if l:

            heapq.heappush(pq,  l)

    

    out = ListNode(None)

    head = out

    while pq:

        l = heapq.heappop(pq)

        head.next = l

        head = head.next

        if l and l.next:

            heapq.heappush( pq, l.next)

        

    return out.next


查看完整回答
反對 回復 2022-05-24
  • 3 回答
  • 0 關注
  • 502 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號