递归python函数中的持久对象

编程入门 行业动态 更新时间:2024-10-28 01:23:32
本文介绍了递归python函数中的持久对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个递归函数,该函数需要在递归时存储和修改对象(例如集合).我应该在函数内使用全局名称吗?另一种选择是修改或继承函数参数的类,以便它可以保留这个持久对象,但我觉得它不优雅.如果我完全放弃递归,我也可以使用堆栈......

I am trying to write a recursive function that needs to store and modify an object (say a set) as it recurses. Should I use a global name inside the function? Another option is to modify or inherit the class of the parameter of the function so that it can keep this persistent object but I don't find it elegant. I could also use a stack if I would forgo the recursion altogether...

有没有pythonic的方法来做到这一点?发电机可以做到这一点吗?

Is there a pythonic way of doing this? Could a generator do the trick?

推荐答案

只需通过递归方法传递您的持久对象即可.

Just pass through your persistent object through the recursive method.

def recursivemethod(obj_to_act_on, persistent_obj=None): if persistent_obj == None: persistent_obj = set() # Act on your object return recursivemethod(newobj, persistent_obj)

更多推荐

递归python函数中的持久对象

本文发布于:2023-05-23 14:45:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   函数   持久   对象   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!