修改递归函数,无需复制粘贴python
我发现我想修改特定输入的递归函数的行为。我知道我可以通过重写函数来做到这一点,但由于函数可能很长,我想避免重复代码。
举个例子,假设我已经通过以下递归方式实现了函数 lambda x: max(x, 10) :
def orig_fun(x):
if x < 10:
return orig_fun(x + 1)
return x
但现在我想在输入时返回 20是5
,如下所示,与
def desired_fun(x):
if x == 5:
return 20
if x < 10:
return orig_fun(x + 1)
return x
在orig_fun
的begining中添加if语句或编写一个复制orig_fun
主体的新函数相同代码>.我不想这样做,因为正文必须有很多很多行。当然,执行 new_fun = lambda x: 20 if x == 5 else orig_fun(x)
不起作用,因为 new_fun(3)
将是 3
代码>而不是<代码>20。
有什么办法可以在Python3中解决这个问题吗?
请注意,这是 Extend recursive (library) function without code duplication 的重复,没有令人满意的答案(一些用户谈到未呈现“hacky 方式”)
I found that I want to modify a recursive function's behavior for a specific input. I know I can do this by rewriting the function, but as the function could be long I want to avoid duplicating code.
As an example, let's say I have implemented the function lambda x: max(x, 10)
in the following recursive way:
def orig_fun(x):
if x < 10:
return orig_fun(x + 1)
return x
but now I want to return 20
whenever the input is 5
, as in the following
def desired_fun(x):
if x == 5:
return 20
if x < 10:
return orig_fun(x + 1)
return x
which is the same as adding an if statement in the begging of orig_fun
or writing a new function copying the body of orig_fun
. I don't want to do this because the body must be many many lines. Of course, doing new_fun = lambda x: 20 if x == 5 else orig_fun(x)
does not work because new_fun(3)
would be 3
instead of 20
.
Is there a way I can solve this in Python3?
note that this is a duplicate of Extend recursive (library) function without code duplication which has no satisfying answer (some user talked about "hacky ways" not presented)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用另一个函数来包装您的主函数,如下所示:
更新
,以便您想要更改(扩展)递归函数中的逻辑而不触及它,然后让我们使您的递归函数成为非递归函数!
You can use a another function to wrap your main function like that:
update
so you want to change (extend) logic in your recursive function without touching it, then let's make your recursive function non-recursive!