469,331 Members | 5,817 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,331 developers. It's quick & easy.

fifo queue

hi,

how would u improve this code?

class queue:
def __init__(self, size=8):
self.space = size
self.data = [None]*self.space
self.head = 0
self.tail = 0
self.len = 0
def __len__(self): return self.len
def push(self, x):
if self.len==self.space:
self.data.extend( self.data[:self.tail] )
self.data.extend( [None]* (self.space-self.tail) )
self.tail+=self.space
self.space*=2
self.data[self.tail]=x
self.tail+=1
if self.tail==self.space:
self.tail=0
self.len+=1
def pop(self):
if self.len:
elem = self.data[self.head]
self.head+=1
if self.head==self.space:
self.head=0
return elem
def top(self):
if self.len==0:
raise Exception, 'queue is empty'
return self.data[self.head]

thx in adv.

Mar 18 '07 #1
4 5113
Unless the queue is really large, just use the pop operation to get
stuff off the top of the queue. That causes O(n) operations but it
should be fast if n is small.

class queue(list):
push = append
def pop(self):
return list.pop(self,0)

should do about what you wrote.
Mar 18 '07 #2
drochom schreef:
hi,

how would u improve this code?

class queue:
...
I think I'd use collections.deque [1] instead of using a ring buffer as
you're doing (I think) and doing a lot of manual bookkeeping.

[1] http://docs.python.org/lib/deque-objects.html

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Mar 18 '07 #3
Paul Rubin <http://ph****@NOSPAM.invalidwrote:
Unless the queue is really large, just use the pop operation to get
stuff off the top of the queue. That causes O(n) operations but it
should be fast if n is small.

class queue(list):
push = append
def pop(self):
return list.pop(self,0)

should do about what you wrote.
If it IS large, then:

import collections
class queue(collections.deque):
push = collections.deque.append
pop = collections.deque.popleft

could be even better.
Alex
Mar 18 '07 #4
"drochom" <dr*****@googlemail.comwrote:
>
how would u improve this code?
I would add at least one comment...
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Mar 20 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Luca | last post: by
2 posts views Thread by Michele Moccia | last post: by
8 posts views Thread by Jack | last post: by
5 posts views Thread by Dinsdale | last post: by
4 posts views Thread by David Bear | last post: by
reply views Thread by kmoeWW | last post: by
2 posts views Thread by Spoon | last post: by
5 posts views Thread by akenato | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.