简体   繁体   中英

How do I get all consecutive substrings of a string with recursion?

This is the iterative version. How do I get the same result with a recursive code?

def it(word):
  set1 = set()
  for begin in range(len(word)):
      for end in range(begin,len(word)):
         set1.add(word[begin:end+1])
return set1

This is what I have, but it doesn't give every substring back

def recursievesubstring(string):
   lijst = []
   if len(string) == 0:
       lijst.append("")
   else:
       i = 0
       if len(string) > 1:
            midden = len(lijst)//2
            lijst.append(string[midden+1])
       while i < len(string):
            lijst.append(string[:i])
            lijst.append(string[i:])
            recursievesubstring(string[i:-i])
            i+=1
  return lijst

def main():
    string = input("Geef een woord: ")
    print(recursievesubstring(string))

You need to make helper methods that can take more arguments. (Tail recursion) If the restriction is to write a recursive function, you can't use any for or while loops.

what make this complicated is that you have a double iteration, so one way to attack this making a recursive function for each loop and combine them, this mean a auxiliary function that handle the inner loop and the main one that handle the outer loop.

To that end we need to understand the working of the iterative function, a simple print will help

def it(word):
    set1 = set()
    for begin in range(len(word)):
        for end in range(begin,len(word)):
            set1.add(word[begin:end+1])
            print(word[begin:end+1])
        print()
    return set1

and a simple test reveal a useful pattern

>>> x=it("abcdef")
a
ab
abc
abcd
abcde
abcdef

b
bc
bcd
bcde
bcdef

c
cd
cde
cdef

d
de
def

e
ef

f

>>> 

which make the objective more clear, the auxiliary function take a string and either remove the last character or take a sub-string more larger each time, while the main function would remove the first character in each recursive call.

Now I would not give you an working code, but a template, that use tail recursion , for you to complete

def recur_aux(word, result=None, end=None):
    if result is None:
        result = set()
    if end is None:
        end = # an adequate default value
    if #an adequate stop condition, aka base case:
        return result
    else:
        #do an adequate step
        return recur_aux( word, result, #end + or - 1 )

def recur(word,result=None):
    if result is None:
        result = set()
    if word: #this is equivalent to len(word)!=0
        #do a adequate step calling recur_aux
        return recur( # an adequate recursive call )
    else:
        return result

give it a try, and test it like this for example

>>> it("abcdef") == recur("abcdef")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM