PYTHON Return a list from a recursive function

假如想象 提交于 2020-01-07 03:45:09

问题


I'm coding a program, a part of the program is that I want to create a list with all the substring from a string, using a recursive function.

However, when I return the list, I get nothing. The variable substringList has None value.

How can I return the list, without losing all the data in it?

def main(string):
    substringList = []
    substringList = substring(string, substringList)

def substring(string, substringList):#Recursive function to create all the
    length = len(string)             #substrings**strong text**

    if length == 0:
        return substringList

    else:
        substringList.append(string)
        substring(string[1::], substringList)


string = "bananas"
main(string)

回答1:


You got "None" value because you forgot to use the return command. Also, why are you writing a separate wrapper function to call your recursive function? You can do that easily enough in the main program. You can list the default value of substringList in the calling profile with =[]. New code:

def substring(string, substringList=[]):
    # Recursive function to create all the substrings
    #   of the given string

    if len(string) == 0:
        return substringList

    else:
        substringList.append(string)
        substring(string[1:], substringList)
        return substringList

print substring("bananas")

Now, note that you also haven't written logic to get all of the substrings: you've taken only the ones ending with the final letter. The way you stated the problem, you need the others as well, such as "nan", "n", etc. I hope that's what you're attacking next. Note that you might want more recursion: a second call that finds what you get from chopping off the end of this list instead. Is that enough of a hint to get you going?




回答2:


Is this what you were looking for?

def main(string):
    substringList = []
    substringList = substring(string, substringList)
    return substringList
def substring(string, substringList):#Recursive function to create all the
    length = len(string)             #substrings**strong text**

    if length == 0:
        return substringList

    else:
        substringList.append(string)
        substring(string[1::], substringList)
        return substringList


string = "bananas"
main(string)

>>>['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's']


来源:https://stackoverflow.com/questions/34077645/python-return-a-list-from-a-recursive-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!