码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构:优先队列 基于堆实现(python版)

时间:2016-12-03 18:32:08      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   sift   nbsp   父节点   last   object   enqueue   while   int   

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 class PrioQueueError(ValueError):
 5     pass
 6 
 7 class PrioQueue(object):
 8     def __init__(self, elist = []):
 9         self._elems = list(elist)
10         if elist:
11             self.buildheap()
12 
13     def is_empty(self):
14         return not self._elems
15 
16     def peek(self):
17         if self.is_empty():
18             raise PrioQueueError("in peek")
19         return self._elems[0]
20 
21     def enqueue(self, e):
22         self._elems.append(None)
23         self.siftup(e, len(self._elems) - 1)
24 
25     def siftup(self, e, last):
26         elems ,i, j = self._elems, last, (last-1)//2 #父节点
27         while i > 0 and e < elems[j]:
28             elems[i] = elems[j]
29             i, j = j, (j-1)//2
30         elems[i] = e
31 
32     def dequeue(self):
33         if self.is_empty():
34             raise PrioQueueError("in dequeue")
35         elems = self._elems
36         e0 = elems[0]
37         e = elems.pop()
38         if len(elems) > 0:
39             self.siftdown(e, 0, len(elems))
40         return e0
41 
42     def siftdown(self, e, begin, end):
43         elems, i, j = self._elems, begin, begin*2+1
44         while j < end:
45             if j+1 < end and elems[j+1] < elems[j]:
46                 j += 1
47             if e < elems[j]:
48                 break
49             elems[i] = elems[j]
50             i, j = j, 2*j + 1
51         elems[i] = e
52 
53     def buildheap(self):
54         end = len(self._elems)
55         for i in range(end//2, -1, -1):
56             self.siftdown(self._elems[i], i, end)
57 
58 
59     def buildheap(self):
60         end = len(self._elems)
61         for i in range(end//2, -1, -1):
62             self.siftdown(self._elems[i], i, end)
63 
64 if __name__=="__main__":
65     pq = PrioQueue([3,5,2,7,6,9,8,1,0])
66     print(pq._elems)
67     for i in range(9):
68         print(pq.dequeue())

 

数据结构:优先队列 基于堆实现(python版)

标签:style   sift   nbsp   父节点   last   object   enqueue   while   int   

原文地址:http://www.cnblogs.com/xautxuqiang/p/6129198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!