Python Tutorial

Showing posts with label Queue. Show all posts
Showing posts with label Queue. Show all posts

Saturday, October 17, 2015

python heapq/priority queue/Min heap


Python heapq provides implementation of the heap(min) queue algorithm, also known as the priority queue algorithm. Here's some example code.
from heapq import heappush, heappop

# priority queue normal
h = []
heappush(h, 5)
heappush(h, 1)
heappush(h, 3)

print heappop(h),"size",len(h)
print heappop(h),"size",len(h)
print heappop(h),"size",len(h)

# priority queue with tuple number and string
h = []
heappush(h, (5, "sample text"))
heappush(h, (1, "important text"))
heappush(h, (1, "a important text"))
heappush(h, (9, "un-important text"))

print heappop(h)
print heappop(h)

# priority queue with tuple number only 
h = []
heappush(h, (5, 3))
heappush(h, (7, 3))
heappush(h, (1, 3))
heappush(h, (1, 1))
heappush(h, (1, 2))
heappush(h, (3, 2))
heappush(h, (3, 1))

print heappop(h)
print heappop(h)
print heappop(h)

Output:
1 size 2
3 size 1
5 size 0
(1, 'a important text')
(1, 'important text')
(1, 1)
(1, 2)
(1, 3)

Thursday, August 26, 2010

python queue data structure


Queue implementation using collections.deque.
All source code available on github

#DA_Queue.py

from collections import deque
class MyQueue:
    queue = deque()

    def enqueue(self, value):
        self.queue.append(value)
    def dequeue(self):
        if len(self.queue):
            return self.queue.popleft()
        print "Impossible"


myQueue = MyQueue()
myQueue.enqueue(8)
myQueue.enqueue(4)
print myQueue.queue
myQueue.dequeue()
myQueue.dequeue()
print myQueue.queue
myQueue.dequeue()
print myQueue.queue


Output:
deque([8, 4])
deque([])
Impossible
deque([])