Python cookbook (data structure and algorithm) to find the maximum or minimum N elements implementation method example, pythoncookbook

Source: Internet
Author: User

Python cookbook (data structure and algorithm) to find the maximum or minimum N elements implementation method example, pythoncookbook

This example describes how to find the maximum or minimum N elements in python. We will share this with you for your reference. The details are as follows:

Problem:To find the maximum or minimum N elements in a collection

Solution:In the heapq modulenlargest()Andnsmallest()The two functions are exactly what we need.

>>> import heapq>>> nums=[1,8,2,23,7,-4,18,23,42,37,2]>>> print(heapq.nlargest(3,nums))[42, 37, 23]>>> print(heapq.nsmallest(3,nums))[-4, 1, 2]>>>

These two functions accept a parameter key, allowing it to work on a more complex data structure:

# example.py## Example of using heapq to find the N smallest or largest itemsimport heapqportfolio = [ {'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=lambda s: s['price'])expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])print(cheap)print(expensive)
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more 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 you are looking for a maximum or minimum of N elements, and the number of elements in the set is N hours, the following functions have better performance.

These functions first convert data to a list at the underlying layer, and the elements are arranged in the heap order.

>>> Import heapq >>> nums = [, 7,-,] >>>> heap = list (nums) >>> heap [1, 8, 2, 23, 7,-4, 18, 23, 42, 37, 2] >>> heapq. the heapify (heap) # heapify () parameter must be a list. This function changes the list to a heap for real-time operations. In this way, heap functions can be used in any situation. >>> Heap [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]> heapq. heappop (heap) # The following is a small 3rd element-4> heapq. heappop (heap) 1 >>> heapq. heappop (heap) 2 >>>

The most important feature of heap is that heap [0] is always the smallest element. Availableheapq.heappop()It is easy to find the minimum value. The complexity of this operation is O (logN), and N represents the heap size.

Summary:

1. When the number of elements to be searched is relatively small, the functionnlargest()Andnsmallest().
2. If you only want to find the minimum and maximum values (N = 1), using min () and max () will be faster.
3. If N is about the same size as the set, the faster method is to sort the set and then slice it (for examplesorted(items)[:N]Orsorted(items)[-N:])
4. heapq. heappush (heap, item): press the item into the heap array heap. If you do not perform this step, the heappop () is invalid;
Heapq. heappop (heap): extracts the smallest value from the heap array and returns it.
Heapq. heapify (list): The parameter must be list. This function changes the list to heap for real-time operations. In this way, heap functions can be used under any circumstances.
Heapq. heappushpop (heap, item): A combination of heappush and heappop. note: heappush (heap, item) is first operated, and heappop (heap) is then operated)
Heapreplace (heap, item): a joint operation between heappop (heap) and heappush (heap, item. Note: The difference between heappushpop (heap, item) and heappushpop is that the order is different. Here we delete the item first and press it into the heap.
Heap, merge (* iterables)

>>> H = [] # define a list >>> from heapq import * # introduce the heapq module >>> h [] >>> heappush (h, 5) # add values to the heap> heappush (h, 2)> heappush (h, 3)> heappush (h, 9)> h # h value [2, 5, 3, 9] >>> heappop (h) # Delete the smallest value from h and return the value 2 >>> h [3, 5, 9] >>> h. append (1) # Note: if it is not pushed into the heap, append a value through append> h # The heap function cannot operate on the added value, or its heap does not exist [3, 5, 9, 1] >>> heappop (h) # The minimum value that can be found from h is 3, instead of 13 >>> heappush (h, 2) # in this case, not only is 2 pushed to the heap, but 1 also enters the heap. >>> H [1, 2, 9, 5] >>> heappop (h) # The operation object already contains 11
>>> H [1, 2, 9, 5] >>> heappop (h) 1 >>> heappushpop (h, 4) # Add 4 to delete the minimum value 2 at the same time and return the minimum value, which is equivalent to the following operations: 2 # heappush (h, 4), heappop (h) >>> h [4, 5, 9]
>>> A = [3, 6, 1] >>> heapify (a) # after converting a into a heap, you can operate on it >>> heappop () 1 >>> B = [, 5] # If B is not a heap, the result is displayed as follows >>> heappop (B) # in sequence, delete the first value and return the result. The minimum value 4 is not selected from the result. >>> heapify (B) # changes to heap, and then the operation >>> heappop (B) 2
>>> A = [] >>> heapreplace (a, 3) # If the list is empty, Traceback (most recent call last): File "<stdin> ", line 1, in <module> IndexError: index out of range >>> heappush (a, 3) >>> a [3] >>> heapreplace (a, 2) # Delete (heappop (a)-> 3), then add (heappush (a, 2) 3 >>> a [2] >>> heappush (, 5) >>> heappush (a, 9) >>> heappush (a, 4) >>> a [2, 4, 9, 5] >>> heapreplace (, 6) # first locate the minimum value from heap a and return it, then add 62 >>> a [4, 5, 9, 6] >>> heapreplace (a, 1) #1 is later added. Before 1 is added, the minimum value of a is 44> 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]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.