python - 将迭代函数转换为递归函数
问题描述
我正在尝试将此迭代函数转换为递归函数。该函数接受整数 x 和整数列表。for 循环删除列表中的一个元素
def function(x, arr):
for v in arr:
if v % x == 0:
arr.remove(v)
return arr
我试过这样做,但它似乎不起作用:
out = []
def removeMultiples(x, arr):
if len(arr) < 1:
return arr
else:
if arr[0] % x == 0:
out.append(arr[0])
return out + removeMultiples(x, arr[1:])
else:
return out + removeMultiples(x, arr[1:])
解决方案
此函数的迭代版本可以使用列表推导
def function(x, arr):
return [i for i in arr if i % x != 0]
递归版本可能看起来像这样
def removeMultiples(x, arr):
if not arr:
return []
current, rest = arr[0], arr[1:]
if current % x != 0:
return [current] + removeMultiples(x, rest)
else:
return removeMultiples(x, rest)
例如
>>> values = [1,2,3,4,5,6,7,8]
>>> function(2, values)
[1, 3, 5, 7]
>>> removeMultiples(2, values)
[1, 3, 5, 7]
请注意,这两个版本都创建并返回一个新列表,而不是从现有列表中删除元素。
推荐阅读
- libreoffice-calc - 有没有办法配置 Libreoffice,以便引用空单元格的单元格也显示一个空单元格?
- reactjs - Material-UI - 在DataTable中获取数据显示=>“React.useState”不能在回调中调用
- java - 如何扫描所有目录并获取在kotlin中以给定扩展名结尾的文件名和路径列表
- security - 在一个简单的程序中重命名本地绝对文件路径并上传到 github,这样没人知道我的目录,这有关系吗?
- vuetify.js - Vuetify 更改全局悬停/活动颜色
- javascript - 导致 RangeError 的 Node.Js 模块中的变量和模块范围:超出最大调用堆栈大小
- python - python中线性回归函数的输入问题(输入包含NaN,无穷大或对于dtype('float64')来说太大的值。)
- python - 如何减少python中重复优化约束的已用内存?
- rest - Postman Google API 请求给出“401:未经授权”
- c# - 如何在机器人框架 4 中使用文本提示?