Home > other >  Implementing Python's split() function using purely recursion
Implementing Python's split() function using purely recursion

Time:01-17

I have a problem that I have been completely stumped on for the better part of a day.

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 delimeter 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 would really appreciate help on this specific problem! Thank you!

EDIT: To be completely clear, the use of any loops or additional parameters is prohibited. Further, string functions such as index() or find() are also prohibited since they are essentially loops. Helper functions are not allowed either.

CodePudding user response:

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)


assert my_split("hello,there,world", ",") == ["hello", "there", "world"]
assert my_split("hello world!", ",") == ["hello world!"]
assert my_split("hello world!", " ") == ["hello", "world!"]

CodePudding user response:

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', ','))
  •  Tags:  
  • Related