Find all substrings in a string using recursion Python 3 -


how make list of possible substrings in string using recursion? (no loops) know can recurse using s[1:] cut off first position , s[:-1] cut off last position. far have come this:

def lst_substrings(s):   lst = []   if s == "":     return lst   else:     lst.append(s)     return lst_substrings(s[1:]) 

but make list of substrings sliced first position if worked

fun problem, here's solution - feedback appreciated.

output

in [73]: lstsubstrings("hey") out[73]: ['', 'y', 'h', 'hey', 'he', 'e', 'ey'] 

solution

def lstsubstrings(s):     # base case: when s empty return empty string     if(len(s) 0):         return [s]     substrs = []     # string substring of - definition of subset in math     substrs.append(s)     # extend list of substrings substrings first     # character cut out     substrs.extend(lstsubstrings(s[1:]))     # extend list of substrings substrings last      # character cut out     substrs.extend(lstsubstrings(s[:-1]))     # convert list `set`, removing duplicates, , convert      # list     substrs = list(set(substrs))      return substrs 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -