-2

Hi I am trying to find all possible substrings within a string

For example, if

string = 'abc'

I would like output to be

['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']

This is a solution that works from

Getting all combinations of a string and its substrings (thank you @davidlowryduda)

def subs(string, ret=['']):
    if len(string) == 0:
        return ret
    head = string[0]
    tail = string[1:]
    ret = ret + list(map(lambda x: x+head, ret))   #this is the line I have problem with
    return subs(tail, ret)

and this is my code (I am trying not to use map or lambda function)

def addhead (ret, head):
        for i in ret:
            i += str(head)
        return ret

def subs2(string, ret=['']):
    if len(string) == 0:
        return ret
    head = string[0]
    tail = string[1:]
    ret = ret + addhead(ret,head)    #this is the line that I changed
    return subs(tail, ret)

However the output is now

['', '', 'b', 'b', 'c', 'c', 'bc', 'bc']

Does anyone knows what went wrong?

Thank you!

WXYZ
  • 53
  • 2
  • 9
  • Could you use `itertools.combinations` here? eg: `output = [''.join(el) for n in range(len(string) + 1) for el in itertools.combinations(string, n)]`... – Jon Clements Nov 23 '19 at 15:53
  • Your code looks like it's calling the old function: `return subs(...)` Is that a typo? – Mark Nov 23 '19 at 15:54
  • Hi Mark! Nope it wasnt a typo I was doing a recursive function – WXYZ Nov 26 '19 at 08:51

1 Answers1

1

It should be

def addhead(ret, head):
    results = []

    for i in ret:
        results.append( i + str(head) )

    return results

You have to create new list with results and then return this list


Rest is the same - if you only uses return subs2(...) instead of return subs(...)


Full code:

def addhead(ret, head):
    results = []
    for i in ret:
        results.append(i + head)
    return results

def subs2(string, ret=['']):
    if len(string) == 0:
        return ret
    head = string[0]
    tail = string[1:]
    ret = ret + addhead(ret, head)
    return subs2(tail, ret)

print(subs2('abc'))
furas
  • 134,197
  • 12
  • 106
  • 148