简体   繁体   English

如何从递归 function 返回列表?

[英]How to return the a list from a recursive function?

I'm trying to return a list from the following recursive function, where should I do it?.我正在尝试从以下递归 function 返回一个列表,我应该在哪里做?。 I think I cant manage to do it because I do not fully understand all the function steps so how can I follow each step of the recursion using the debugger?我想我无法做到这一点,因为我不完全理解 function 的所有步骤,那么如何使用调试器跟踪递归的每个步骤? (pycharm) Thanks for the helpers!! (pycharm)感谢帮助者!

def parentheses_helper(open, close, word, lst):
    """ get 2 equal integers and return all the combination of balanced parantheses """
    if open == 0 and close == 0:
        lst.append(word) 
        print(lst)
    if open > close:
        return
    if open > 0:
        parentheses_helper(open - 1, close, word + '(', lst)
    if close > 0:
        parentheses_helper(open, close - 1, word + ')', lst)


def parentheses(n):
    parentheses_helper(n, n, '', [])

If you need to return the list from function parentheses you can create a list variable inside of it and pass to parentheses_helper and then return the variable.如果您需要从 function parentheses返回列表,您可以在其中创建一个列表变量并传递给parentheses_helper ,然后返回该变量。 This will work, because you are modifying the same list inside of parentheses_helper (the list is not getting copied)这将起作用,因为您正在修改parentheses_helper内的相同列表(该列表未被复制)

def parentheses(n):
    lst = []
    parentheses_helper(n, n, '', lst)
    return lst

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM