Daily python - heapsort module heapq python in

The heapq python module provides operations related to the heap sort, understanding of the heap may be its own online search for knowledge, the need is clear that, in python is the smallest heap heap-based, so the corresponding pop operation, will pop up wherein the smallest element, some of the methods provided below the modules run.

First of all, how to create a heap, usually initialized to create a stack according to a list, which requires the function heapify () to complete, for the empty list we can direct it in accordance with the heap to treat and operate accordingly, non-empty list must be appropriate to create operating.

>>> from heapq import *
>>> h =[5,4,3,2,1]
>>> heapify(h)
>>> h
[1, 2, 3, 5, 4]

heappush(heap, item)

The value of the item is pressed into the stack

>>> heappush(h, 6)
>>> h
[1, 2, 3, 5, 4, 6]

heappop(heap)

Returns the minimum heap

>>> heappop(h)
1
>>> h
[2, 4, 3, 5, 6]

heappushpop(heap, item)

First item is pressed into the stack value, a minimum value and then return stack

>>> heappushpop(h, 7)
2
>>> h
[3, 4, 7, 5, 6]

heapreplace(heap, item)

In contrast with the above first pop operation performed, then the operation push

>>> heapreplace(h, 8)
3
>>> h
[4, 5, 7, 8, 6]

merge(*iterable)

The more ordered list merge into an ordered list, similar to merge sort, cut remember an ordered list

>>> a =[1,3,5]
>>> b =[2,4,6]
>>> list(merge(a,b))
[1, 2, 3, 4, 5, 6]

nlargest(n, iterable[, key]), nsmallest(n, iterable[,key])

Get a list of the minimum and maximum values ​​of n, key value can specify a particular keyword sorting

portfolio = [
    {'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'])

More exciting, attention to "gnaw home"

5873968-290afe05f96971c6.png
Ye home

Reproduced in: https: //www.jianshu.com/p/7748b78699a8

Guess you like

Origin blog.csdn.net/weixin_33727510/article/details/91251343