Simple implementation of LRU cache Python

Source: Internet
Author: User

LRU (Least Recently Used) has not been Used for the longest time

In computing, cache algorithms (also frequently called cache replacement algorithms or cache replacement policies) are optimizing instructions-or algorithms-that a computer program or a hardware-maintained structure can follow in order to manage a cache of information stored on the computer. when the cache is full, the algorithm must choose which items to discard to make room for the new ones. -- Wikipedia

Update:

Recently, I saw a question about LRUCache in Leetcode.

Design and implement a data structure for Least Recently Used (LRU) cache.

It shoshould support the following operations: get and set.

Get (key)-Get the value (will always be positive) of the key if the key exists in the cache, otherwise return-1.

Set (key, value)-Set or insert the value if the key is not already present. when the cache reached its capacity, it shocould invalidate the least recently used item before inserting a new item.

The following is the implementation: (The code can be found on Github)

Class LRUCache (object ):
Def _ init _ (self, capacity ):
"""
: Type capacity: int
"""
Self. capacity = capacity
Self. _ values = {}
Self. _ access = []

Def get (self, key ):
"""
: Rtype: int
"""
If key in self. _ values:
Self. _ access. remove (key)
Self. _ access. append (key)
Return self. _ values [key]
Else:
Return-1

Def set (self, key, value ):
"""
: Type key: int
: Type value: int
: Rtype: nothing
"""
If not self. capacity:
Return
If key in self. _ values:
Self. _ access. remove (key)
Else:
While len (self. _ values)> = self. capacity:
Self. cleanup ()
Self. _ access. append (key)
Self. _ values [key] = value

Def cleanup (self ):
Del self. _ values [self. _ access. pop (0)]
Use Python to implement LRUCacheDict

Fixed dict capacity
Record the last access time and expiration time of each key
When you add/query operations, dict is cleared. The expired key is cleared first, and the earliest accessed key is cleared.
Specific implementation:

The following code can be found on Github:

Import time
From collections import OrderedDict


Class LRUCacheDict (object ):
Def _ init _ (self, expiration = 15*60, maxsize = 128 ):
Self. expiration = expiration
Self. maxsize = maxsize
Self. _ expire_times = OrderedDict ()
Self. _ access_times = OrderedDict ()
Self. _ values = {}

Def _ setitem _ (self, key, value ):
T = int (time. time ())
Self. _ delitem _ (key)
Self. _ values [key] = value
Self. _ access_times [key] = t
Self. _ expire_times [key] = t + self. expiration
Self. cleanup ()

Def _ getitem _ (self, key ):
T = int (time. time ())
Del self. _ access_times [key]
Self. _ access_times [key] = t
Self. cleanup ()
Return self. _ values [key]

Def _ delitem _ (self, key ):
If key in self. _ values:
Del self. _ values [key]
Del self. _ access_times [key]
Del self. _ expire_times [key]

Def size (self ):
Return len (self. _ values)

Def clear (self ):
Self. _ values. clear ()
Self. _ access_times.clear ()
Self. _ expire_times.clear ()

Def cleanup (self ):
T = int (time. time ())
For key, expire in self. _ expire_times.iteritems ():
If expire <t:
Self. _ delitem _ (key)

While self. size ()> self. maxsize:
For key in self. _ access_times:
Self. _ delitem _ (key)
Break

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.