提问人:RXEsquivel 提问时间:7/13/2023 更新时间:7/13/2023 访问量:37
记忆函数中嵌套函数的用途让我感到困惑。聪明人明白吗?
Purpose of nested function within memoization function is confusing me. Does someone smart understand?
问:
“内部”函数在下面做什么?仅仅是因为“返回内部”需要包含在“memoize_factorial”函数中吗?
memory = {}
def memoize_factorial(f):
# This inner function has access to memory
# and 'f'
def inner(num): # WHAT DOES this "inner" FUNCTION DO?
if num not in memory:
memory[num] = f(num)
print('result saved in memory')
else:
print('returning result from saved memory')
return memory[num]
return inner # WHAT DOES "inner" MEAN?
@memoize_factorial
def facto(num):
if num == 1:
return 1
else:
return num * facto(num-1)
print(facto(5))
print(facto(5)) # directly coming from saved memory
我从这篇 Geeks for Geeks 文章中得到了这段代码:https://www.geeksforgeeks.org/memoization-using-decorators-in-python/
我试着看看我是否能像一个成年人一样理解这段代码中发生的事情,但在 45 分钟的方形大脑之后,我决定问问大脑不那么方形的更聪明的人。
答: 暂无答案
评论
return inner # WHAT DOES "inner" MEAN?
,嗯,是一个局部变量,它指的是你刚才在语句上方定义的函数inner
return
def inner
memoize_factorial
用作装饰器。(参见 ?这意味着它本质上充当了 .通过这样做,这意味着任何打电话的人实际上都会打电话。 检查是否已看到该参数。如果没有,它将调用原始文件(传递给装饰器)并将其存储在内存中。@memoize_factorial
facto
return inner
facto
inner
inner
f
def foo(x): return x
fact(5)
foo(5)
120
5
memory = {}
memoize_factorial