简体   繁体   中英

PYTHON Return a list from a recursive function

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)

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?

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']

Prune's answer above has an issue; however, I have yet to earn enough points to comment so here goes. If you run the following the result from the second call will include the results of the first call concatenated with the first call. Ie

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"))
print (substring("two"))

Results in :

['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's'] ['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's', 'two', 'wo', 'o']

I think below is a simpler solution to your problem and also fixes the issue pointed out by gordonC.

def substring(stringList):
    # Recursive function to create all the substrings of the given string
    last_str = stringList[-1]
    if len(last_str) == 1:
        return stringList
    else:
        return substring(stringList + [last_str[1:]])


print(substring(["bananas"]))
print(substring(["two"]))
print(substring(["what"]))

The output is

['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's']
['two', 'wo', 'o']
['what', 'hat', 'at', 't']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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