Performing specialized searches
using a binary heap
As with BST, you have many ways to implement a binary heap. Writing one by
hand or using a dictionary does work well, but relying on a package makes things
considerably faster and more reliable. The
heapq
package comes with Python, so
you don’t even need to install it. You can find the documentation for this package
at
https://docs.python.org/3/library/heapq.html
. The following example
shows how to build and search a binary heap using
heapq
:
import heapq
data = {3:'White', 2:'Red', 1:'Green', 5:'Orange',
4:'Yellow', 7:'Purple', 0:'Magenta'}
heap = []
for key, value in data.items():
heapq.heappush(heap, (key, value))
heapq.heappush(heap, (6, 'Teal'))
heap.sort()
CHAPTER 7
Do'stlaringiz bilan baham: |