【发布时间】:2020-03-26 12:52:53
【问题描述】:
作为一个新的 Python 程序员,我正在练习 Leetcode 的 LRU 缓存问题 链接:https://leetcode.com/problems/lru-cache/
问题描述:
为最近最少使用 (LRU) 缓存设计和实现数据结构。它应该支持以下操作:get 和 put。
get(key) - 如果缓存中存在键,则获取键的值(始终为正),否则返回 -1。 put(key, value) - 如果键不存在,则设置或插入值。当缓存达到其容量时,它应该在插入新项目之前使最近最少使用的项目无效。
Leetcode 提供的解决方案如下:
from collections import OrderedDict
class LRUCache(OrderedDict):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self:
return - 1
self.move_to_end(key)
return self[key]
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self:
self.move_to_end(key)
self[key] = value
if len(self) > self.capacity:
self.popitem(last = False)
但是我在提交代码时遇到了以下错误:
第 29 行:AttributeError:“LRUCache”对象没有属性“_OrderedDict__root”
谁能给我一些提示,为什么会出现这个错误?真的很感激吗?
【问题讨论】:
-
你的代码中有第 29 行吗?那是哪几行?
-
请提供一个最小的、可重现的例子。 stackoverflow.com/help/minimal-reproducible-example
标签: python class ordereddictionary