First, let's fix your function into an iterative version that works.
def substring(strings):
final = []
for string in strings:
while string:
final.append(string)
string = string[1:]
return final
Next, let's move the final variable into the arguments so that recursive calls to the function can build upon the list.
def substring(strings, final=None):
if final is None: final = []
for string in strings:
while string:
final.append(string)
string = string[1:]
return final
The next step is to convert the for loop into recursion. We can see that the base case is when the list strings is empty, and the recursive case is to work on each element of strings. For the recursive case here we'll extract the first element of strings and pass the rest of the list to the recursive call.
def substring(strings, final=None):
if final is None: final = []
# base case: empty list
if not strings: return final
# recursive case:
# work on first string in list
string = strings[0]
# add all substrings to final
while string:
final.append(string)
string = string[1:]
return substring(strings[1:], final)
Converting the while loop into recursion is a similar process: find the base case (empty string) and the recursive case (adding a single substring to final), and make a recursive call for the recursive case.
def substring(strings, final=None):
if final is None: final = []
if not strings: return final
string = strings[0]
if not string: return substring(strings[1:], final)
final.append(string)
strings[0] = string[1:]
return substring(strings, final)
And finally, a bit of cleanup.
def substring(strings, final=None):
if final is None: final = []
if not strings: return final
if not string[0]: return substring(strings[1:], final)
final.append(string)
strings[0] = string[0][1:]
return substring(strings, final)
[]andappend. Use()and+.