[英]Why is this recursive map function using all available memory?
I am trying to implement the map function in Python using recursion, running it on Google Colab.我正在尝试使用递归在 Python 中实现 map 函数,并在 Google Colab 上运行它。
def randfun(var):
return var * 2
def mapr(f, itr):
if len(itr) == 1:
return f(itr[0])
else:
amendedlist = list(mapr(randfun, f(itr[1:])))
#print(amendedlist)
return amendedlist
li = [1,2,3,4,5]
result = mapr(randfun, li)
print(result)
The error I'm getting is this: Your session crashed after using all available RAM
.我得到的错误是:
Your session crashed after using all available RAM
。 It produces a bunch of logs, which I can't decrypt, but am happy to reproduce.它产生了一堆日志,我无法解密,但很高兴重现。
Looks like the code is failing to halt the recursion and it goes on infinitely, but again I'm not sure.看起来代码无法停止递归并且它无限地继续,但我又不确定。 What am I doing wrong?
我究竟做错了什么?
This worked for me这对我有用
def randfun(var):
return var * 2
def mapr(f, itr):
if len(itr) == 1:
return [f(itr[0])]
amendedlist = [f(itr[0])] + mapr(f, itr[1:])
return amendedlist
li = [1,2,3,4,5]
result = mapr(randfun, li)
print(result) #[2, 4, 6, 8, 10]
When you recurse, you need to pass a shorter list to mapr()
, eg itr[1:]
.当您递归时,您需要将较短的列表传递给
itr[1:]
mapr()
,例如itr[1:]
。 But you're passing f(itr[1:])
instead.但是您正在传递
f(itr[1:])
。 When itr == [1, 2, 3, 4, 5]
, f(itr[1:])
is f([2, 3, 4, 5])
which is [2, 3, 4, 5, 2, 3, 4, 5]
.当
itr == [1, 2, 3, 4, 5]
, f(itr[1:])
是f([2, 3, 4, 5])
即[2, 3, 4, 5, 2, 3, 4, 5]
。 So the argument is getting shorter, not longer, and you never reach the base case.所以争论越来越短,而不是越来越长,你永远不会达到基本情况。
The recursion should just pass itr[1:]
, not f(itr[1:])
since the arguments to f()
should be list elements, not the list itself.递归应该只传递
itr[1:]
,而不是f(itr[1:])
因为f()
的参数应该是列表元素,而不是列表本身。
Your base case is also wrong.你的基本情况也是错误的。
mapr()
must always return a list, but in the base case you're just returning the result of the function without wrapping it into a list. mapr()
必须始终返回一个列表,但在基本情况下,您只是返回函数的结果而不将其包装到列表中。
It would be best to use an empty list as the base case, so the function works for empty lists.最好使用空列表作为基本情况,因此该函数适用于空列表。
def mapr(f, itr):
if len(itr) == 0:
return []
else:
amendedlist = [f(itr[0])] + mapr(f, itr[1:])
#print(amendedlist)
return amendedlist
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.