递归倒转列表,我不了解输出

发布于 2025-02-09 20:00:12 字数 589 浏览 1 评论 0原文

嗨,当我尝试使用这种递归方法将列表反向列表时,我对为什么ANS的输出为何感到有些困惑。根据调试器的说法,ANS在函数上是正确的,但是当它退出RS函数时突然变化。

”在此处输入图像说明”

enter image description here

Hi, I am a little confused on why the output for ans is 'hello' when I am trying to reverse the list using this recursive method. According to the debugger, ans is correct in the function, but suddenly changes when it exits the rs function.
enter image description here

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

飘过的浮云 2025-02-16 20:00:12

一些观察结果:

  • reversestring()应该具有返回类型none,因此行返回ANS不需要
  • ans 看起来不错,但是根据注释阅读“不要返回任何东西,改为定位”,您需要修改s;您可以使用(略微隐秘)语句s [:] = ans来执行此操作,该语句(感谢字符)代替了s 使用ANS
  • 谈到语法,这不是关键,但是您可以使用s [1:](只有一个<一个<代码>:),而不是s [1 ::]

更新的代码(我分配了listlist,以保存def reversestring()的语句):

List = list
class Solution:
    def reverseString(self, s: List[str]) -> None:
        ans=[]
        def rs(s, ans):
            if len(s) == 0:
                return
            a = s[0]
            rs(s[1:], ans)
            ans.append(a)
        rs(s, ans)
        s[:] = ans


x = Solution()
s = [c for c in 'hello']
print('input:', s, sep='\n')
x.reverseString(s)
print('output:', s, sep='\n')

输出:

input:
['h', 'e', 'l', 'l', 'o']
output:
['o', 'l', 'l', 'e', 'h']

A few observations:

  • reverseString() is supposed to have return type of None, so the line return ans is not needed
  • the logic for ans looks fine, but based on the comment reading "Do not return anything, modify s in-place instead", you need to modify s; you can do this using the (slightly cryptic) statement s[:] = ans, which (thanks to the : character) replaces the contents of s with those of ans
  • speaking of : syntax, this is not critical, but you can use s[1:] (just one :) instead of s[1::]

Updated code (I have assigned List to be list, to preserve the def statement of reverseString()):

List = list
class Solution:
    def reverseString(self, s: List[str]) -> None:
        ans=[]
        def rs(s, ans):
            if len(s) == 0:
                return
            a = s[0]
            rs(s[1:], ans)
            ans.append(a)
        rs(s, ans)
        s[:] = ans


x = Solution()
s = [c for c in 'hello']
print('input:', s, sep='\n')
x.reverseString(s)
print('output:', s, sep='\n')

Output:

input:
['h', 'e', 'l', 'l', 'o']
output:
['o', 'l', 'l', 'e', 'h']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文