Python: implement split() using recursion

Viewed 157

Lately I tried to figure out a question implementing split() function, objective is to complete a function that split a string with delimiters such as "-" or a path string with "/"s to a list of words in a recursive manner.

inputString = "Hello-World"
expectedOutput = ["Hello", "World"]

Tried the solution using find(), is there any other possible solution without using linear functions?

def splitString(str, delim):
  list=[]
  i=str.find(delim)
  if i!=-1:
    list.append(str[0:i])
    newStr=str[i+1:]
    list.extend(splitString(newStr, delim))
  else:
    list.append(str)
  return list
1 Answers

It would be best not to use camelCase to name functions and variables in Python. Anyway, you can split a string into words with recursion something like this:

input_string = "Hello-World"
words = []

def split_string(string, delim, head=''):
    if string:
        if string[0] == delim:
            words.append(head)
            return split_string(string[1:], delim)
        else:
            return split_string(string[1:], delim, head + string[0])
    else: 
        words.append(head)
        return ''

split_string(input_string)
print(words)
Related