In the following code, I've tried to make a recursive function to find substrings of a given string.
i = 0
j = 0
def substrings(string):
global i, j
if j == len(string) - 1 or len(string) == 0:
return []
elif i == len(string):
j = j + 1
i = j + 1
return [string[j:i]] + substrings(string)
i += 1
return [string[j:i]] + substrings(string)
>>> substrings('ceng')
>>> ['c', 'ce', 'cen', 'ceng', 'e', 'en', 'eng', 'n', 'ng', 'g']
I always tend to use globals while working with recursions, and I don't like it at all. Is there anything I can do not to use globals in this case? I know I can pass the variables to the function as parameters, but it doesn't work for me since the function is supposed to have only one parameter.
Also, if there is a way of doing this without any variable at all, I'd like to learn that too.