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