1

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']

1
  • Good catch, I missed a restriction. Helper functions are not allowed either! Commented Jan 17, 2022 at 2:10

2 Answers 2

1

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

Comments

0
def mySplit(string, delim):
    if string.count(delim) == 0:
        return [string]
    idx = string.index(delim)
    return [string[:idx]] + mySplit(string[idx + 1:], delim)


print(mySplit('hello,there,world', ','))

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.