Python Return A List From A Recursive Function
Solution 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 stringiflen(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?
Solution 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']
Solution 3:
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. I.e.
def substring(string, substringList=[]):
# Recursive function to create all the substrings
# of the given stringiflen(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']
Solution 4:
I think below is a simpler solution to your problem and also fixes the issue pointed out by gordonC.
defsubstring(stringList):
# Recursive function to create all the substrings of the given string
last_str = stringList[-1]
iflen(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']
Post a Comment for "Python Return A List From A Recursive Function"