Data Structures in Python: Lists and Tuples - Lists and Tuples in the Real World
(Page 4 of 4 )
The example application will implement a ring buffer or a bounded buffer using a list. In a bounded buffer, once the capacity is full, then the first element i.e. the oldest element is replaced with newest element. The implementation uses a class switch pattern. Here is the code:
class RingBuffer(object):
""" class that implements a not-yet-full buffer """
def __init__(self, size_max):
self.max = size_max
self.data = [ ]
class __Full(object):
""" class that implements a full buffer """
def append(self, x):
""" Append an element overwriting the oldest one. """
self.data[self.cur] = x
self.cur = (self.cur+1) % self.max
def tolist(self):
""" return list of elements in correct order. """
return self.data[self.cur:] + self.data[:self.cur]
def append(self, x):
""" append an element at the end of the buffer. """
self.data.append(x)
if len(self.data) == self.max:
self.cur = 0
# Permanently change self's class from non-full to full
self.__class__ = __Full
def tolist(self):
""" Return a list of elements from the oldest to the newest. """
return self.data
The class defines an empty list as a buffer. The nested class __Full implements the logic to overwrite the oldest element if the buffer is full. The tolist method returns the list in the correct order. Next the append method of the outer class i.e. RingBuffer appends a new item to the end of the list. It also checks whether the length of the buffer is equal to the maximum size. If it is equal, then the buffer's state is changed to full. The tolist method returns the buffer. The following is a sample implementation that shows how to use the RingBuffer class:
if __name__ == '__main__':
x = RingBuffer(5)
x.append(1); x.append(2); x.append(3); x.append(4)
print x.__class__, x.tolist( )
x.append(5)
print x.__class__, x.tolist( )
x.append(6)
print x.data, x.tolist( )
x.append(7); x.append(8); x.append(9); x.append(10)
print x.data, x.tolist( )
That brings us to the end of this discussion. List and tuple are the basic data structures found in Python. On the basis of these, more complex structures such as trees can be developed. How to implement them will be a topic for discussion in the future. Till then…
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |