Python's implementation cache ring

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.