Problem: Want to find the largest or smallest n elements in a collection
Solution: The Nlargest () and nsmallest () two functions in the HEAPQ module are exactly what we need.
Import HEAPQ>>> nums=[1,8,2,23,7,-4,18,23,42,37,2]print(heapq.nlargest (3, nums) ) [heapq.nsmallest (3, nums)]print[ -4, 1, 2]>>>
These two functions accept a parameter key, which allows it to work on more complex data structures:
#example.py##Example of using HEAPQ to find the N smallest or largest itemsImportHeapqportfolio= [ {'name':'IBM','shares': 100,' Price': 91.1}, {'name':'AAPL','shares': 50,' Price': 543.22}, {'name':'FB','shares': 200,' Price': 21.09}, {'name':'HPQ','shares': 35,' Price': 31.75}, {'name':'YHOO','shares': 45,' Price': 16.35}, {'name':'ACME','shares': 75,' Price': 115.65}]cheap= Heapq.nsmallest (3, Portfolio, key=Lambdas:s[' Price']) Expensive= Heapq.nlargest (3, Portfolio, key=Lambdas:s[' Price'])Print(cheap)Print(expensive)
Python 3.4.0 (V3.4.0:04f714765c13, Mar, 19:24:06) [MSC v.1600 32bit (Intel)] on Win32type"Copyright","credits" or "license ()" forMore information.>>> ================================ RESTART ================================>>> [{'name':'YHOO',' Price': 16.35,'shares': 45}, {'name':'FB',' Price': 21.09,'shares': 200}, {'name':'HPQ',' Price': 31.75,'shares': 35}][{'name':'AAPL',' Price': 543.22,'shares': 50}, {'name':'ACME',' Price': 115.65,'shares': 75}, {'name':'IBM',' Price': 91.1,'shares': 100}]>>>
If the largest or smallest n element is being searched, and N is very small compared to the number of elements in the collection, the following function performs better.
These functions first convert the data to a list at the bottom, and the elements are arranged in the order of the heap.
>>>ImportHEAPQ>>> nums=[1,8,2,23,7,-4,18,23,42,37,2]>>> heap=list (nums)>>>heap[1, 8, 2, 23, 7,-4, 18, 23, 42, 37, 2]>>> heapq.heapify (Heap)#The heapify () parameter must be a list, which changes the list to a heap and operates in real time. Functions that enable the use of heaps in any situation. >>>heap[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]>>>heapq.heappop (heap)#如下是为了找到第3小的元素-4>>>heapq.heappop (Heap)1>>>heapq.heappop (Heap)2>>>
The most important feature of Heap is that heap[0] is always the smallest element. The minimum value can be easily found by Heapq.heappop(), the complexity of this operation is O (Logn), and N is the size of the heap.
Summarize:
1. function nlargest () and Nsmallest () are most suitable when the number of elements to be searched is relatively small.
2. Using min () and Max () is faster if you just want to find the minimum and maximum values (n=1).
3. If N is similar to the size of the set itself, the quicker way is to sort the collection before slicing (for example, using sorted (items) [: N] or sorted (items) [N:])
4. Heapq.heappush (heap, item): The item is pressed into the heap array heap. If this step is not performed, the Heappop () later fails;
Heapq.heappop (heap): Removes the smallest value from the heap array heap and returns.
Heapq.heapify (list): The parameter must be a list, which changes the list to a heap and operates in real time. Functions that enable the use of heaps in any situation.
Heapq.heappushpop (Heap, item): It is the combination of the above Heappush and heappop, and the function of both. Note: the equivalent of the first operation of the Heappush (Heap,item), and then Operation Heappop (Heap)
Heapreplace (Heap, item): Is a joint operation of Heappop (heap) and Heappush (Heap,item). Note that the difference from Heappushpop (Heap,item) is that the order is different, here is the first delete, then press into the heap
Heap,merge (*iterables)
>>> h=[]#Define a list>>> fromHeapqImport*#Introducing the HEAPQ module>>>h[]>>> Heappush (h,5)#add values to the heap in turn>>> Heappush (h,2)>>> Heappush (h,3)>>> Heappush (h,9)>>> h#the value of H[2, 5, 3, 9]>>> Heappop (h)#removes the smallest from H and returns the value2>>>h[3, 5, 9]>>> H.append (1)#Note that if you do not press into the heap, you append a value by append>>> h#The function of the heap does not manipulate the added value, or it does not exist in terms of the heap .[3, 5, 9, 1]>>> Heappop (h)#the minimum value that can be found from H is 3, not 13>>> Heappush (h,2)#at this point, not only the 2 is pressed into the heap, but also 1 into the heap. >>>h[1, 2, 9, 5]>>> Heappop (h)#the operand already contains 11
>>> h[1, 2, 9, 5]>>> heappop (h)1>>> Heappushpop (h,4) # Add 4 to delete the minimum value 2 and return the minimum value, equivalent to the following:2 #heappush (h,4), Heappop (h)>>> h[4, 5, 9]
>>> a=[3,6,1]>>> heapify (a) # After you turn A into a heap, you can manipulate it >>> Heappop (a)1>>> b=[4,2,5] #B is not a heap, and if you manipulate it, the results are shown below >>> Heappop (b) # in order, the first value is deleted and returned, and the smallest 4>>> heapify (b) # is not picked up and then manipulated >>> Heappop (b)2
>>> a=[]>>> Heapreplace (a,3)#If the list is empty, an errorTraceback (most recent): File"<stdin>", Line 1,inch<module>Indexerror:index out of range>>> Heappush (a,3)>>>a[3]>>> Heapreplace (a,2)#Delete (Heappop (a)->3) first, then join (Heappush (a,2))3>>>a[2]>>> Heappush (a,5) >>> Heappush (a,9)>>> Heappush (a,4)>>>a[2, 4, 9, 5]>>> Heapreplace (a,6)#first find the minimum value from heap A and return, then add 62>>>a[4, 5, 9, 6]>>> Heapreplace (a,1)#1 is added later, before 1, the minimum value in a is 4 .4>>>a[1, 5, 9, 6]
>>> a=[2,4,6] >>> b=[1,3,5]>>> c=merge (A, b)>>> list (c) [1, 2, 3, 4, 5, 6]
"Python Cookbook" "Data Structure and algorithm" 4. Find the largest or smallest n elements