0
def lst_substrings(s,ans):
    if len(s) == 0:
        print(ans)
    ch=s[0]
    ros=s[1:]
    
    lst_substrings(ros,ans)
    lst_substrings(ros,ans+ch)

s="binod"
ans=" "
lst_substrings(s,ans)

I tried to find list of sub-strings through recursion in python. But I get an error message like this-

Traceback (most recent call last):
  File "<string>", line 12, in <module>
File "<string>", line 7, in lst_substrings
  File "<string>", line 7, in lst_substrings
  File "<string>", line 7, in lst_substrings
  [Previous line repeated 2 more times]
  File "<string>", line 4, in lst_substrings
IndexError: string index out of range

This same logic fetches result in cpp. I want to go through this approach. Can someone please help me in modifying the code?

Chandrachud Pati
  • 425
  • 1
  • 5
  • 12
  • what's the expected output for input string: "aabc" ? – Moinuddin Quadri Dec 29 '20 at 19:26
  • Please show us some example inputs and the expected outputs. – Flux Dec 29 '20 at 19:27
  • Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – mkrieger1 Dec 29 '20 at 19:27
  • 1
    When the length of the string is 0, `lst_substrings` should **return** in order to skip `ch=s[0]`. – mkrieger1 Dec 29 '20 at 19:28
  • Please provide sample outputs for a string. For the function itself, the `base case` and `recursive case` need to be better thought out. – anurag Dec 29 '20 at 19:31
  • The exception occurs because `print` does not exit the function, so `s[0]` is still attempted. – Karl Knechtel Aug 14 '22 at 17:27

2 Answers2

1

I don't understand what is the expected return, however the error is caused by the fact that the function never returns, hence adding a return will fix the IndexError

EDIT Better to append the results of ans in a separate list as shown below

result = []
def lst_substrings(s, ans):
    if len(s) == 0:
        print(ans)
        result.append(ans)
        return
    ch = s[0]
    ros = s[1:]

    lst_substrings(ros, ans)
    lst_substrings(ros, ans + ch) 


s = "binod"
ans = " "
lst_substrings(s, ans)
for item in result:
    print(item)
Federico Baù
  • 6,013
  • 5
  • 30
  • 38
1

As a general rule, you should separate rendering (printing) from computing results. This would make the function much simpler and avoir the need to use side effects on a global list that doesn't belong to the function.

# computing (as a generator)
def getSubStrings(S):
    for i in range(1,len(S)): yield S[:i]
    if S: yield from getSubStrings(S[1:])

# rendering (i.e. printing results)        
for ss in getSubStrings(s):print(ss)

b
bi
bin
bino
i
in
ino
n
no
o
Alain T.
  • 40,517
  • 4
  • 31
  • 51