Looking at your expected output, a summary of the program might be:
- Write all the substrings belonging with the first char of the input string (
a ab abc)
- Write all the remaining substrings (
b bc c)
In Python-ish pseudocode:
def substrings(input):
output = substrings_using_first_char(input)
return output + substrings(input[1:])
substrings_using_first_char(), I will leave to you. It could be recursive, but there is an easy non-recursive implementation using a for loop. You could write the recursive version as an exercise.
There's a problem with the code above, however -- it always calls itself, so it will never return, and will overflow the stack. All recursive functions/methods require a stopping condition. So put one in:
def substrings(input):
if(input == ''):
return []
else:
output = substrings_using_first_char(input)
return output + substrings(input[1:])
This fits the universal format for recursive functions/methods:
recursiveMethod(input):
if(input is simple case with easy answer):
return answer for the simple case
else:
split input into a "small piece" and the "rest"
return answer made by working with "small piece" and
recursiveMethod(rest)
The whole thing can be tidied a bit, to remove the intermediate variable:
def substrings(input):
if(input == ''):
return []
else:
return substrings_using_first_char(input) + substrings(input[1:])
I have made it return a list, rather than print to the screen, because this is generally a cleaner way to code, but you can adapt it to your needs.
Note that since Python doesn't optimize tail recursion, stack overflow is always a risk in Python. Recursion is useful (especially when working with trees) but when there's an obvious iterative solution, in Python it's usually better to use that.