簡體   English   中英

如何從帶有堆的列表列表中找到小於數字的最少項目?

[英]how can I find the minumm of items which is less than a number from list of lists with heap?

我今天考試出了一道題。 考慮一下我有一個這樣的列表:

[[0, 0], [95, 1], [0, 5], [200, 3], [1000, 4], [300, 2]]

如何找到 ele[0] 值小於某個值且 ele[1] 是其中最小值的元素? 示例:如果輸入n=100? 那么[0, 0], [95, 1], [0, 5]ele[0]值小於100 ,並且[0,0]是最小值。 所以輸出應該是[0,0]這個問題希望我們用堆來做,但我不知道怎么做。 任何幫助,將不勝感激。

要在 Python 中實現最小堆,您可以使用 heapq 模塊,它提供用於創建和操作最小堆的函數。 這是一個示例,說明如何使用最小堆在 ele[0] 值小於特定值的元素中找到 ele[1] 的最小值的元素:

import heapq

def find_min_ele(lst, n):
    # create a min-heap
    heap = []
    # add elements to the heap
    for ele in lst:
        if ele[0] < n:
            heapq.heappush(heap, ele[1])
    # find the minimum element
    min_value = heapq.heappop(heap)
    for ele in lst:
        if ele[1] == min_value:
            return ele

lst = [[0, 0], [95, 1], [0, 5], [200, 3], [1000, 4], [300, 2]]
n = 200
print(find_min_ele(lst, n))

在此示例中, find_min_ele 函數將元素列表和值 n 作為參數。 它創建一個最小堆,並將 ele[0] 值小於 n 的元素中的 ele[1] 值添加到堆中。 最后,它通過調用 heappop 函數從堆中返回最小值。

這是一個有效的解決方案:

from heapq import heappush as push, heappop as pop

def find_min_ele(lst, n):
    h = []
    for a, b in lst:
        if a < n:
            push(h, [b, a])  # reverse!
    return pop(h)[::-1]  # reverse again


>>> find_min_ele([[95, 1], [0, 5], [200, 3], [1000, 4], [300, 2]], 200)
[95, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM