I have a priority queue class that has only few functions like, if it is empty or not, push and pop an itme into it. But I need to check if a partuclar item is present in the queue or not? how would I do that??
+1
A:
If you are storing the queue items in a List inside your class you could just search the list. There are many ways to do this.
>> list = ["item1", "item2", "item3"]
["item1", "item2", "item3"]
>> matches = filter(lambda x: x == "item2", list)
["item2"]
>> count = len(b)
1
>> found = len(b) > 0
True
Also
>> list.count("item2")
1
>> list.index("item3")
2
Hope it helps. Otherwise you could post some code if you want more specific help.
tarn
2010-07-22 06:25:14
I am not storing the elements of queue in any list? do i need to do that? I mean, when I do push, I need to put that entry into list also.
Shilpa
2010-07-22 06:30:02
I am guessing you will need to store the items in some way, maybe a list. If you post a sample of what your doing perhaps we can help a little more.
tarn
2010-07-22 06:38:41
+2
A:
I don't kno which type of priority queue, you use but you amy be interested by heapq in teh standard lib : http://docs.python.org/library/heapq.html
It makes possible to use a priority queue in the same way you use a list:
from heapq import heappush
l = []
heappush(l, 'D')
heappush(l, 'B')
heappush(l, 'A')
print l
>>> ['A', 'B', 'D']
UPDATE: When using the priority queue as a list, you can use the 'in' statement
print 'B' in l
>>> True
print 'C' in l
>>> False
luc
2010-07-22 06:25:55
this is an excellent point! but it doesn't answer OPs question: How to check if an item is present in the queue or not: Use the `in` operator?
Daren Thomas
2010-07-22 06:30:01
Oups! The usage of 'in' is implicit when I say "It makes possible to use a priority queue in the same way you use a list". But you are right: explicit is better than implicit :)
luc
2010-07-22 07:08:26
But I'm guessing his priority queue class is an exercise and therefore he can't just use the `heapq`...
Daren Thomas
2010-07-22 09:21:50
+2
A:
If you are using the heapq
from the standard library (and thus lists to represent your queue), you can use the in
operator:
if item in myqueue:
print "yay!"
Daren Thomas
2010-07-22 06:28:45
iterable argument required - this is the error I m getting when I used...index in pq
Shilpa
2010-07-22 06:49:31
then your priority queue class is not iterable... try implementing iteration for your priority queue class: http://docs.python.org/library/stdtypes.html#iterator-types
Daren Thomas
2010-07-22 09:19:32