Python uses heapq to implement a small top heap (finding up to N elements) and pythonheapq

Source: Internet
Author: User

Python uses heapq to implement a small top heap (finding up to N elements) and pythonheapq

Find up to N elements-heap Data Structure

The sequence is given, and the top k elements are obtained. The heapq module is used for implementation.

When heappush () is used, the heap sequence of elements is maintained when new elements are added from the data source.
Delete an existing element in an operation and replace it with a new value. You can use heapreplace ()

Import heapq

Class BtmkHeap (object ):
Def _ init _ (self, k ):
Self. k = k
Self. data = []

Def Push (self, elem ):
# Reverse elem to convert to max-heap
Num1 = elem [0]
Num1 =-num1
Num2 = elem [1]
# Using heap algorighem
If len (self. data) <self. k:
Heapq. heappush (self. data, (num1, num2 ))
Else:
Topk_small = self. data [0] [0]
If elem [0]> topk_small:
Heapq. heapreplace (self. data, (num1, num2 ))

Def BtmK (self ):
Return sorted ([(-x [0], x [1]) for x in self. data])


If _ name _ = '_ main __':
A = (100,1)
B = (200,2)
C =)
D = (400,4)
E = (50, 5)
Btm = BtmkHeap (3)
Btm. Push ()
Btm. Push (B)
Btm. Push (c)
Btm. Push (e)
Btm. Push (23,1 ))
Print (btm. BtmK ())



Result [(23, 1), (50, 5), (100, 1)]

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.