Are there Python code for a FIFO-like structure?

Will Ware wware at world.std.com
Thu Oct 5 23:13:44 EDT 2000


Huaiyu Zhu (hzhu at users.sourceforge.net) wrote:
> I need something like a fifo, inplemented in a fixed length list...
> an IndexError is raised if the tail gets
> too close to the head.

I'm not aware of any standard thing like that. Generally one would
implement a stack using list.append() and list.pop(), and I have
implemented FIFOs using list.append() and list.pop(0), but I hadn't
faced the constraint of keeping the list length constant.

Since you can't do a put and a get literally simultaneously, you'll
have to tolerate a list length that oscillates between two adjacent
values. It might be useful to whip up a state diagram telling when
it's OK to do a put or a get based on the current list length. You'll
need to alternate puts and gets to prevent greater length variations.
See if this does what you want:

class FixedLengthFifo:
    def __init__(self, length):
        self.length = length
        self.lst = length * [None]
    def put(self, x):
        if len(self.lst) != self.length:
            raise IndexError
        self.lst.append(x)
    def get(self):
        if len(self.lst) != self.length + 1:
            raise IndexError
        return self.lst.pop(0)

-- 
# - - - - - - - - - - - - - - - - - - - - - - - -
# Resistance is futile. Capacitance is efficacious.
# Will Ware	email:    wware @ world.std.com



More information about the Python-list mailing list