gpt4 book ai didi

Python函数相乘时出现递归错误

转载 作者:行者123 更新时间:2023-12-01 08:46:48 24 4
gpt4 key购买 nike

我正在使用 python 3 并尝试在 for 循环中乘以函数。我编写了一个简单的示例代码来演示我的问题。我想要这段代码做的是从函数 x^2 开始,然后在第一个循环中将其乘以 x^2,得到 x^4。然后再次将 x^4 与 x^2 相乘,得到 x^6 等

fun = lambda x: x**2

function = lambda x: x**2
for i in range(2):
function = lambda x: function(x) * fun(x)

print(function(2))

但是代码出现递归错误。我不知道这是如何导致递归的?任何帮助都感激不尽。

最佳答案

循环中的赋值相当于:

def function(x):
return function(x) * fun(x)

这是一个没有停止条件的递归函数。由于 python's binding rules,您对 function 的初始定义被隐藏了。 :

The following constructs bind names: formal parameters to functions, import statements, class and function definitions (these bind the class or function name in the defining block)

您可以使用python3 -m trace --trace script.py来跟踪它并验证此类行为:

--- modulename: script, funcname: <lambda>
script.py(6): function = lambda x: function(x) * fun(x)
--- modulename: script, funcname: <lambda>
script.py(6): function = lambda x: function(x) * fun(x)

# Repeated until a RecursionError is thrown

您可以将函数绑定(bind)为 lambda 的参数:

fun = lambda x: x**2
function = lambda x: x**2
for i in range(2):
function = lambda x, y=function: y(x) * fun(x)

print(function(2))

这将产生以下跟踪:

--- modulename: script, funcname: <module>
script.py(3): fun = lambda x: x**2
script.py(4): function = lambda x: x**2
script.py(5): for i in range(2):
script.py(6): function = lambda x, y=function: y(x) * fun(x)
script.py(5): for i in range(2):
script.py(6): function = lambda x, y=function: y(x) * fun(x)
script.py(5): for i in range(2):
script.py(8): print(function(2))
--- modulename: script, funcname: <lambda>
script.py(6): function = lambda x, y=function: y(x) * fun(x)
--- modulename: script, funcname: <lambda>
script.py(6): function = lambda x, y=function: y(x) * fun(x)
--- modulename: script, funcname: <lambda>
script.py(4): function = lambda x: x**2
--- modulename: script, funcname: <lambda>
script.py(3): fun = lambda x: x**2
--- modulename: script, funcname: <lambda>
script.py(3): fun = lambda x: x**2
64

关于Python函数相乘时出现递归错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53270796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com