Look at Codebokk. The second version through Python to implement the cache ring, after absorption record, convenient for later review.
Task:
Defines a fixed-size cache that, when filled, overwrites the first (oldest) element with the newly added element. This data structure is useful for storing logs and historical information.
Solution:
When the cache fills up, the cache object is modified in a timely fashion, making it a cache class that fills up from the filled cache class.
The implementation code is as follows:
1 classRingclass:2 """3 define a cache class that is not filled4 """5 def __init__(self, Size_max):6Self.size =Size_max7Self.data = []8 9 class __full:Ten "" " One define a fill cache when processing A "" " - defAppend (self, x): -Self.data[self.cur] =x theSelf.cur = (self.cur+1)%self.size - - defToList (self): - returnself.data[self.cur:]+Self.data[:self.cur] + - defAppend (self, x): + self.data.append (x) A ifLen (self.data) = =self.size: atSelf.cur =0 -Self.__class__= self.__full """A permanent cache class that fills the current class switch, the critical part""" - defToList (self): - returnSelf.data
The usage example code is as follows:
1 if __name__=="__main__":2x = Ringbuff (5)3X.append (1); X.append (2); X.append (3); X.append (4)4 PrintX.__class__, X.tolist ()5X.append (5)6 PrintX.__class__, X.tolist ()7X.append (6)8 PrintX.__class__, X.data, X.tolist ()9X.append (7); X.append (8); X.append (9): X.append (10)Ten PrintX.__class__, X.data,x.tolist ()
An example of the final result is as follows:
Since the buffer ring has a fixed size, when it fills up, adding new elements will overwrite the oldest element it holds. This transformation is accomplished through self.__class__ = Self.__full. It is useful in practical applications. Record, convenient for later review!
Python's implementation cache ring