fifo queue

D

drochom

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.
 
P

Paul Rubin

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.
 
A

Alex Martelli

Paul Rubin said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top