Home > OS >  Python:Splitting the input string with delimiters to list of words by recursion
Python:Splitting the input string with delimiters to list of words by recursion

Time:01-25

Lately I tried to figure out a question about string separation, it requires to complete a function that split a string with delimiters of "-"s to a list of words by recursion, .find() or .split(), and any "linear-time" methods are not allowed to use.

inputString = "Tadokoro-Kouji-114514"
expectedOutput = ["Tadokoro", "Kouji", "114514"]

I've tried the solution using .find(), but since it iwas not allowed I was kinda ran out of tricks.

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

CodePudding user response:

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 = "Tadokoro-Kouji-114514"
words = []

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

split_string(input_string)
print(words)
  •  Tags:  
  • Related