3/18/2014

Python Study, queue, stack, priority queue, example source code

import queue

def GetItemList(q):
    ret = []
    n = q.qsize()
    while n>0:
        ret.append(q.get())
        n -= 1
    return ret

l = 'apple,banana,orange'


#queue test
q = queue.Queue()
for x in l.split(','):
    print(x)
    q.put(x)

print( GetItemList(q) )


#stack case
#LIFO last in first out
q = queue.LifoQueue()
for x in l.split(','):
    q.put(x)
print( GetItemList(q) )


#priorityQueue
q = queue.PriorityQueue()
q.put((5,"apple"))
q.put((10,"banana"))
q.put((1,"orange"))
print( GetItemList(q) )

"""
out put is...
['apple', 'banana', 'orange']
['orange', 'banana', 'apple']
[(1, 'orange'), (5, 'apple'), (10, 'banana')]
"""