使用纯递归实现 Python 的 split() 函数
Implementing Python's split() function using purely recursion
我正在尝试使用递归实现 Python 的 split()
函数,没有附加参数,也没有循环。
对于给定的输入字符串,这是所需的输出
mySplit('hello,there,world', ',')
=> ['hello', 'there', 'world']
这是我目前的尝试,但它实际上只是删除了分隔符并将字符串放入列表中,但我不知道如何将项目附加到列表中!
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]]
此代码导致 ['hellothereworld']
我会这样写:
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]
编辑: 哎呀,跳过了你问题的关键部分。我认为这可行。
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)
编辑 2: 这肯定是一个棘手的问题。真正有趣的问题。希望我不会再遇到这个问题:
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!"]
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', ','))
我正在尝试使用递归实现 Python 的 split()
函数,没有附加参数,也没有循环。
对于给定的输入字符串,这是所需的输出
mySplit('hello,there,world', ',')
=> ['hello', 'there', 'world']
这是我目前的尝试,但它实际上只是删除了分隔符并将字符串放入列表中,但我不知道如何将项目附加到列表中!
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]]
此代码导致 ['hellothereworld']
我会这样写:
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]
编辑: 哎呀,跳过了你问题的关键部分。我认为这可行。
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)
编辑 2: 这肯定是一个棘手的问题。真正有趣的问题。希望我不会再遇到这个问题:
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!"]
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', ','))