【问题标题】:Python Error: OrderedDict Object Has No Attribute OrderedDict RootPython 错误:OrderedDict 对象没有属性 OrderedDict Root
【发布时间】: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”

谁能给我一些提示,为什么会出现这个错误?真的很感激吗?

【问题讨论】:

标签: python class ordereddictionary


【解决方案1】:

你应该选择python3作为编译语言。 OrderedDict 在 python3 中有一些新属性

【讨论】:

  • 如果您能介绍其中的一些新属性,那就太好了。
猜你喜欢
  • 1970-01-01
  • 2012-11-15
  • 1970-01-01
  • 2019-09-12
  • 2018-01-19
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
  • 2014-07-08
相关资源
最近更新 更多