歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Python的優先權隊列

python的優先權隊列,根據優先權來進行隊列排序,但是注意優先權隊列使用heap實現,而heap不是穩定的排序,所以,想要實現同優先權內部也有序,則需要增加一個計數,表示該優先權的順序。參考以下代碼:

  1. #!/usr/bin/python
  2. from Queue import Queue
  3. from Queue import PriorityQueue
  4. a1='a1'
  5. a2='a2'
  6. a3='a3'
  7. a4='a4'
  8. a5='a5'
  9. b1='b1'
  10. b2='b2'
  11. b3='b3'
  12. b4='b4'
  13. b5='b5'
  14. q = Queue()
  15. pq = PriorityQueue()
  16. for i in xrange(5):
  17.     p = 5 - i
  18.     q.put("a"+str(p))
  19.     q.put("b"+str(p))
  20.     pq.put((p,"a"+str(p)))
  21.     pq.put((p,"b"+str(p)))
  22. for i in xrange(5):
  23.     p = 5 - i
  24.     q.put("a"+str(p)+str(i+5))
  25.     q.put("b"+str(p)+str(i+5))
  26.     pq.put((p,"a"+str(p)+str(i+5)))
  27.     pq.put((p,"b"+str(p)+str(i+5)))
  28. size = q.qsize()
  29. print "queue item size:%s" %size
  30. print "queue items:"
  31. for i in xrange(size):
  32.     print q.get()
  33. size = pq.qsize()
  34. print "priority queue item size:%s" %size
  35. print "priority queue items:"
  36. for i in xrange(size):
  37.     print pq.get()
  38. #"but priority queue with same priority is not queue, if we want so, do the following:"
  39. import itertools
  40. count = itertools.count()
  41. poq = PriorityQueue()
  42. for i in xrange(5):
  43.     p = 5 - i
  44.     poq.put((p,count.next(),"a"+str(p)))
  45.     poq.put((p,count.next(),"b"+str(p)))
  46. for i in xrange(5):
  47.     p = 5 - i
  48.     poq.put((p,count.next(),"a"+str(p)+str(i+5)))
  49.     poq.put((p,count.next(),"b"+str(p)+str(i+5)))
  50. size = poq.qsize()
  51. print "priority ordered queue item size:%s" %size
  52. print "priority ordered queue items:"
  53. for i in xrange(size):
  54.     print poq.get()

輸出類似如下:

  1. queue item size:20
  2. queue items:
  3. a5
  4. b5
  5. a4
  6. b4
  7. a3
  8. b3
  9. a2
  10. b2
  11. a1
  12. b1
  13. a55
  14. b55
  15. a46
  16. b46
  17. a37
  18. b37
  19. a28
  20. b28
  21. a19
  22. b19
  23. priority queue item size:20
  24. priority queue items:
  25. (1, 'a1')
  26. (1, 'a19')
  27. (1, 'b1')
  28. (1, 'b19')
  29. (2, 'a2')
  30. (2, 'a28')
  31. (2, 'b2')
  32. (2, 'b28')
  33. (3, 'a3')
  34. (3, 'a37')
  35. (3, 'b3')
  36. (3, 'b37')
  37. (4, 'a4')
  38. (4, 'a46')
  39. (4, 'b4')
  40. (4, 'b46')
  41. (5, 'a5')
  42. (5, 'a55')
  43. (5, 'b5')
  44. (5, 'b55')
  45. priority ordered queue item size:20
  46. priority ordered queue items:
  47. (1, 8, 'a1')
  48. (1, 9, 'b1')
  49. (1, 18, 'a19')
  50. (1, 19, 'b19')
  51. (2, 6, 'a2')
  52. (2, 7, 'b2')
  53. (2, 16, 'a28')
  54. (2, 17, 'b28')
  55. (3, 4, 'a3')
  56. (3, 5, 'b3')
  57. (3, 14, 'a37')
  58. (3, 15, 'b37')
  59. (4, 2, 'a4')
  60. (4, 3, 'b4')
  61. (4, 12, 'a46')
  62. (4, 13, 'b46')
  63. (5, 0, 'a5')
  64. (5, 1, 'b5')
  65. (5, 10, 'a55')
  66. (5, 11, 'b55')
Copyright © Linux教程網 All Rights Reserved