递归倒转列表,我不了解输出
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一些观察结果:
reversestring()
应该具有返回类型none
,因此行返回ANS
不需要ans 看起来不错,但是根据注释阅读“不要返回任何东西,改为定位”,您需要修改
s
;您可以使用(略微隐秘)语句s [:] = ans
来执行此操作,该语句(感谢:
字符)代替了s 使用
ANS
:
语法,这不是关键,但是您可以使用s [1:]
(只有一个<一个<代码>:),而不是s [1 ::]
更新的代码(我分配了
list
为list
,以保存def
reversestring()
的语句):输出:
A few observations:
reverseString()
is supposed to have return type ofNone
, so the linereturn ans
is not neededans
looks fine, but based on the comment reading "Do not return anything, modify s in-place instead", you need to modifys
; you can do this using the (slightly cryptic) statements[:] = ans
, which (thanks to the:
character) replaces the contents ofs
with those ofans
:
syntax, this is not critical, but you can uses[1:]
(just one:
) instead ofs[1::]
Updated code (I have assigned
List
to belist
, to preserve thedef
statement ofreverseString()
):Output: