Python implementation of LRU algorithm

Source: Internet
Author: User
Tags for in range

Lru:least recently used, the least recently used algorithm. Its use of the scene is: in a limited space to store objects, when the space is full, will be a certain principle to delete the original objects, commonly used principles (algorithms) have LRU,FIFO,LFU and so on. The algorithm is used in both the cache hardware of the computer and in the memory-to-virtual page replacement, and in the Redis cache system. I had this problem in an interview and a written exam.

The LRU algorithm is relatively simple, when the key is accessed (typically query, update, increase, in Get () and set () two methods to implement), put the key to the front of the queue (or the last side) on the line, This allows you to arrange the key in descending (or ascending) order of the time it was last accessed.

In Python, you can use collections. Ordereddict is very convenient to implement the LRU algorithm, of course, if you do not think of using ordereddict, it can be used dict+list to achieve. This article mainly refers to the LRU CACHE in PYTHON, which is very good, it is not only the function, but also simple and easy to read. Method One of the code and reference article is basically the same, method two is I think out, more cumbersome, in fact, ordereddict itself is similar to the mechanism to achieve the order.

Method One: Implement with Ordereddict (recommended)

 fromCollectionsImportordereddictclassLRUCache (ordereddict):def __init__(self,capacity): Self.capacity=capacity Self.cache=ordereddict ()defGet (Self,key):ifSelf.cache.has_key (Key): Value=Self.cache.pop (Key) Self.cache[key]=valueElse: Value=NonereturnvaluedefSet (self,key,value):ifSelf.cache.has_key (Key): Value=Self.cache.pop (Key) Self.cache[key]=valueElse:            ifLen (self.cache) = =Self.capacity:self.cache.popitem ( last= False)#pop out of the first itemSelf.cache[key] =valueElse: Self.cache[key]= value

The test code is as follows

c = LRUCache (5)  for in range (5,10):    c.set (i,10*i)       Print  C.cache, C.cache.keys ()  c.get (5) C.get (7)  Print C.cache, C.cache.keys ()  c.set (10,100)print  c.cache, C.cache.keys ()  C.set (9,44) print C.cache, C.cache.keys ()

The output is as follows

Ordereddict ([(5), (6), (7, 9), (8, 5)])     [6, 7, 8, 6, 9]ordereddict ([(60, 8), (80, 9), (90, 5), (), (7)])     [6, 8, 9, 5, 7]ordereddict ([(8, +), (9, +), (5,), (7,), (+)])   [8, 9, 5, 7, 10]ordered Dict ([8, +], (5, +), (7, 8), (+), (9, ())])   [5, 7, 10, 9,]

Method Two: Implement with Dict+list (not recommended)

classLRUCache (object):def __init__(self,capacity): SELF.L=[] self.d={} self.capacity=Capacity
defGet (Self,key):ifSelf.d.has_key (Key): Value=Self.d[key] Self.l.remove (key) Self.l.insert (0,key)Else: Value=Nonereturnvalue
defSet (self,key,value):ifSelf.d.has_key (Key): Self.l.remove (key)elifLen (self.d) = =Self.capacity:oldest_key=Self.l.pop () self.d.pop (Oldest_key) Self.d[key]=value Self.l.insert (0, key)

The test code is as follows

c = LRUCache (5)  for in range (5,10):    c.set (i,10*i)       Print  c.d,c.l  c.get (5) C.get (7)  print  c.d,c.l  C.set (10,100)print  c.d,c.l  c.set (9,44)print C.d,c.l

Output to

{8:80, 9:90, 5:50, 6:60, 7:70}   [9, 8, 7, 6, 5] {8:80, 9:90, 5:50, 6:60, 7:70}   [7, 5, 9, 8, 6] {5:50, 7:70, 8:80, 9:90, 10:100} [10, 7, 5, 9, 8] {5:50, 7:70, 8:80, 9:44, 10:100} [9, 10, 7, 5, 8]

Reference:

http://www.kunxi.org/blog/2014/05/lru-cache-in-python/

Http://blog.sina.com.cn/s/blog_631d3a630101mhup.html

Python implementation of LRU algorithm

Related Article

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.