<commit_before>---
published: false
layout: post
tags: []
---
## A New Post

Enter text in [Markdown](http://daringfireball.net/projects/markdown/). Use the toolbar above, or click the **?** button for formatting help.<commit_msg>Created 2016-05-05-Python-实现-LRUCache.md<commit_after>---
published: false
layout: post
tags: []
---

``` python
class LRUCache:

    # @param length, an integer
    def __init__(self, length):
        self.cache = {}
        self.used_list = []
        self.length = length

    # @return an integer
    def get(self, key):
        if key in self.cache:
            if key != self.used_list[-1]:
                self.used_list.remove(key)
                self.used_list.append(key)
            return self.cache[key]
        else:
            return -1

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def set(self, key, value):
        if key in self.cache:
            self.used_list.remove(key)
        elif len(self.cache) == self.length:
            self.cache.pop(self.used_list.pop(0))
        self.used_list.append(key)
        self.cache[key] = value
```

从 python3.2 开始内置了 functools.lru_cache，使用 functools 模块的 lur_cache 装饰器，可以缓存最多 maxsize 个此函数的调用结果，从而提高程序执行的效率，特别适合于耗时的函数。
{'fraction_non_alphanumeric': 0.12470023980815348, 'fraction_numerical': 0.010391686650679457, 'mean_word_length': 2.3386666666666667, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4658503', 'n_tokens_mistral': 450, 'n_tokens_neox': 443, 'n_words': 100}