Implementing Python's split() function using purely recursion
I'm attempting to implement Python's split()
function using recursion with no additional parameters and no loops.
For a given input string, this is the desired output
mySplit('hello,there,world', ',')
=> ['hello', 'there', 'world']
Here is my current attempt, but it really only removes the delimiter and places the string in a list, but I cannot figure out how to append items to the list!
def mySplit(string, delim):
if len(string) == 1:
return [string]
if string[0] == delim:
return [mySplit(string[1:], delim)[0]]
return [string[0] + mySplit(string[1:], delim)[0]]
This code results in ['hellothereworld']
I'd write something like:
def my_split(s, delim):
for i, c in enumerate(s):
if c == delim:
return [s[:i]] + my_split(s[i + 1 :], delim)
return [s]
EDIT: Oops, skipped over a crucial part of your question. I think this works.
def my_split(s, delim, i=0):
if i == len(s):
return [s]
elif s[i] == delim:
return [s[:i]] + my_split(s[i + 1 :], delim)
return my_split(s, delim, i + 1)
EDIT 2: It's a tricky one for sure. Really interesting problem. Hopefully I don't hit any more constraints with this one:
def my_split(s, delim):
if not s:
return [""]
elif s[0] == delim:
a = my_split(s[1:], delim)
return "", *a
b, *rest = my_split(s[1:], delim)
return [s[0] + b] + rest
assert my_split("hello,there,world", ",") == ["hello", "there", "world"]
assert my_split("hello world!", ",") == ["hello world!"]
assert my_split("hello world!", " ") == ["hello", "world!"]