3

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
  • 4
    Please avoid using str or list as the name for a variable or function argument. Those are already the name of python's builtin class list and python's builtin class str. If you shadow these names by reusing them for a particular variables, everything becomes confusing. Commented Jan 24, 2022 at 11:12

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.