Issue
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)
Solution
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?
Answered By - Prune
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.