python - 递归列表 Python
问题描述
所以我正在学习 RecursiveLists,我们的教授给了我们一个recursivelist 类的init
class RecursiveList:
# === Private Attributes ===
# _first:
# The first item in the list.
# _rest:
# A list containing the items that come after
# the first one.
_first: Optional[Any]
_rest: Optional[RecursiveList]
# === Representation Invariants ===
# _first is None if and only if _rest is None.
# This represents an empty list.
def __init__(self, items: list) -> None:
"""Initialize a new list containing the given items.
The first node in the list contains the first item in <items>.
"""
if items == []:
self._first = None
self._rest = None
else:
self._first = items[0]
self._rest = RecursiveList(items[1:])
现在我想通过在列表的前面插入一个项目来改变列表,但我不知道该怎么做。我知道以self._rest
递归方式存储列表的其余部分,并且我应该将值移动self._first
into self._rest
,但是如何移动 int 并将其转换为递归函数具有其余部分?
def insert_first(self, item: object) -> None:
"""Insert item at the front of this list.
This should work even if this list is empty.
"""
解决方案
您创建一个新的RecursiveList
(顺便说一句:这通常称为Linked List),将当前值复制到其中,使其rest
指向您的 current rest
,用要插入的元素覆盖您自己的元素,并将您的元素设置rest
为新列表。
就像是:
def insert_first(self, item: object) -> None:
"""Insert item at the front of this list.
This should work even if this list is empty.
"""
if self._first is None:
# handle case where list is "empty"
self._first = item
else:
new = RecursiveList()
new._first = self._first
new._rest = self._rest
self._first = item
self._rest = new
Before:
1:"e" -→ 2:"l" -→ 3:"l" -→ 4:"o"
After:
1:"h" 2:"l" -→ 3:"l" -→ 4:"o"
| ↑
└→5:"e" -┘
请注意,此过程是所谓的恒定时间操作,因为列表有多大并不重要:此过程总是花费大致相同的时间。这(在列表开头的恒定时间插入)对于链接列表来说有些独特,不适用于 Python 的基于数组的普通列表。
推荐阅读
- java - 在 JAVA 中使用 Mockito 模拟依赖类
- angular - NullInjectorError:StaticInjectorError(DynamicTestModule)[ToastrService -> InjectionToken ToastConfig]:在 tslint 角度 8
- php - 联系表格 7 (CF7) 单选按钮以更改 WordPress 上的用户角色
- python - 注册页面无法注册用户
- java - flyway java迁移中的自定义配置参数
- wso2 - 在 wso2 中配置 BPS DB 为 5.9.0 时,我必须在 MySQL 中导入哪些脚本?
- sql - 替换部分序列化数据将数据“重置”为标准设置
- html - AMP HTML 是否允许使用 div 样式?
- magento - 如何在magento 2中的价格后添加通用文本
- erlang - 消息传递时 Erlang 处理“badarg”错误