循环中的返回语句呼叫定义的函数

发布于 2025-02-12 12:02:28 字数 610 浏览 0 评论 0原文

我偶然发现了这个片段,它让我抓了我的头,因为它使用了返回语句,该语句调用正在定义的函数。

该函数逆转括号内包含的子字符串。例如,字符串“ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生来就爱笑 2025-02-19 12:02:28

我不确定他们为什么使用枚举,然后继续使用字符串本身中的索引。枚举为您做到这一点,即:
在这种情况下,刺[i] = v。

def solution(string):
    for i, v in enumerate(string):
        if v == "(":
            start = i
        if v == ")":
            end = i
            return solution(string[:start] + string[start+1:end][::-1] + string[end+1:])
    return string

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.

def solution(string):
    for i, v in enumerate(string):
        if v == "(":
            start = i
        if v == ")":
            end = i
            return solution(string[:start] + string[start+1:end][::-1] + string[end+1:])
    return string
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文