Python (data structures and algorithms [2])

Source: Internet
Author: User

Python (data structures and algorithms [2])

Find N elements at most or at least

The heapq module has two functions: nlargest () and nsmallest (), which can solve our problem.

>>> Print (heapq. nlargest (3, nums) [43, 23, 8] >>> print (heapq. nsmallest (3, nums) [-1, 1, 2] # anotherimport heapqportfolio = [{'name': 'ibm ', 'shares': 100, 'price ': 91.1}, {'name': 'aap', '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) # output [{'shares': 45, 'name ': 'yhoo ', 'price': 16.35}, {'shares': 200, 'name': 'fb', 'price': 21.09}, {'shares': 35, 'name': 'hpq', 'price': 31.75}] [{'shares': 50, 'name': 'aap', 'price': 543.22 }, {'shares': 75, 'name': 'acme ', 'price': 115.65}, {'shares': 100, 'name': 'ibm ', 'price': 91.1}]

A Brief Introduction to the methods in heapq:

Import heapq # heapq. heappush (heap, item) # heap is the element added to the defined heap and item; # eg. heap = [] heapq. heappush (heap, 2) # heap = [2] # heapq. heapify (list) # convert the list to heap # eg. list = [,] heapq. heapify (list) # heapq. heappop (heap) # Delete the smallest value # eg. heap = [2, 4, 3, 5, 7, 8, 9, 6] heapq. heappop (heap) ----> heap = [3, 4, 5, 7, 9, 6, 8] # heapq. heapreplace (heap, item) # Delete the minimum element value and add a new element value # eg. heap = [2, 4, 3, 5, 7, 8, 9, 6] heapq. heapreplace (heap, 11) ------> heap = [2, 3, 4, 6, 8, 5, 7, 9, 11] # heapq. heappushpop (heap, item) # first compares the added element value with the first element value in the heap. If the value is greater than the value, the minimum element is deleted and a new element value is added, otherwise, do not change the heap # eg. condition: item> heap [0] heap = [2, 4, 3, 5, 7, 8, 9, 6] heapq. heappushpop (heap, 9) ----> heap = [3, 4, 5, 6, 8, 9, 9, 7] condition: item heap = [2, 4, 3, 5, 7, 8, 9, 6] heapq. heappushpop (heap, 9) ----> heap = [2, 4, 3, 5, 7, 8, 9, 6] # heapq. merge (...) # Merge multiple heaps # heapq. nlargest (n, heap) # query the maximum element in the heap. n indicates the number of query elements # eg. heap = [2, 3, 5, 6, 4, 8, 7, 9] heapq. nlargest (1, heap) ---> [9] # heapq. nsmallest (n, heap) # queries the smallest element in the heap. n indicates the number of query elements # eg. heap = [2, 3, 5, 6, 4, 8, 7, 9] heapq. nlargest (1, heap) ---> [2]
Sort different data in different ways When the number of elements to be searched is relatively small, nlargest and nsmallest are the most suitable. Just to find the maximum and minimum elements, using min and max is the most appropriate. If the difference between N and the set itself is not big, it is appropriate to sort and slice (sorted (items) [: N], sorted (items) [-N:]). When N is less than the total number of elements, it is suitable to convert the data into a list. The elements are arranged in heap Order (refer to heapq. heapify ()). Implement priority queue
Import heapq # the data structure of the heap. the maximum or minimum element class PriorityQueue: def _ init _ (self): self can be found through the logarithm time. _ queue = [] # initialized list self. _ index = 0 # initialize the index. Compare the elements with the same priority with def push (self, item, priority ): # Add an element (tuples) to the _ queue list through heappush. The default value is a small top heap, so the priority is reversed. # The size of the tuples is one by one, therefore, add _ index as the second comparison item with the same priority; the third item heapq will never be compared. heappush (self. _ queue, (-priority, self. _ index, item) self. _ index + = 1 def pop (self): return heapq. heappop (self. _ queue )[- 1] # The triples (-priority, _ index, Item ('') are displayed. Only the last entry is displayed. # The constructed element class Item: def _ init _ (self, name): self. name = name def _ repr _ (self): return 'item ({! R })'. format (self. name) q = PriorityQueue () q. push (Item ('foo'), 1) q. push (Item ('bar'), 5) q. push (Item ('barm'), 4) q. push (Item ('grok'), 1) print (q. pop () print (q. pop () print (q. pop () print (q. pop ())

Output:

Item('bar')Item('barm')Item('foo')Item('grok')

From the output, we can see that the output is based on the priority, and the first output is smaller according to the index with the same priority (because it is a small top heap and the index value inserted first is small)

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.