循环中的返回语句呼叫定义的函数
我偶然发现了这个片段,它让我抓了我的头,因为它使用了返回
语句,该语句调用正在定义的函数。
该函数逆转括号内包含的子字符串。例如,字符串“ foo(oof(bar))”
有望返回“ foobarfoo”
。
def solution(string):
for i, v in enumerate(string):
if string[i] == "(":
start = i
if string[i] == ")":
end = i
return solution(string[:start] + string[start+1:end][::-1] + string[end+1:])
return string
我对第一个返回
的使用感到困惑。我知道它不能被string =
取代,因为它会打破迭代动态。
但是,为什么返回
循环通过该函数,直到结束而不是脱离循环?
I stumbled upon this snippet and it's got me scratching my head because it uses a return
statement that calls the function that is being defined.
The function reverses the substrings contained within parentheses. For example, the string "foo(oof(bar))"
is expected to return "foobarfoo"
.
def solution(string):
for i, v in enumerate(string):
if string[i] == "(":
start = i
if string[i] == ")":
end = i
return solution(string[:start] + string[start+1:end][::-1] + string[end+1:])
return string
I am confused by the use of the first return
. I understand it cannot be replaced by string =
because it would break the iterative dynamic.
However, why does return
loop through the function until it ends instead of breaking out of the loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定他们为什么使用枚举,然后继续使用字符串本身中的索引。枚举为您做到这一点,即:
在这种情况下,刺[i] = v。
Im not sure why they use enumerate, then proceed to use the index in the string itself. Enumerate does this for you ie:
in this case sting[i] = v.