理解递归字符串反转 [英] Understanding recursive string reversal
问题描述
我使用 Python教程可视化网页来尝试和了解这个函数的流程颠倒了一个字符串:
I'm using the Python Tutorial visualize webpage to try and understand the flow of this function that reverses a string:
text = "hello"
def reverse(text):
if len(text) <= 1:
return text
else:
return reverse(text[1:]) + text[0]
print reverse(text)
我理解这个函数的功能,但即使使用可视化工具,仍然不太清楚函数的最后一行是如何在函数流中操作的,因为它会循环字符串中的字符:
I understand what this function does, but even with the visualizer, I'm still not quite grasping how the last line operates in the function in terms of the flow of the function as it loops through the characters in the string:
return reverse(text[1:]) + text[0]
本身 reverse(text [1:])
返回 o
和 text [0] 返回
h
但是,经验不足以了解功能n设置为使用 [1:]
和 [0]
遍历字符串 - 任何解释都会很大从函数返回的最后一个字符串是如何被理解的'olleh'
But again, not quite experienced enough to understand how the function is set up to loop through the string using [1:]
and [0]
— any explanation would be greatly appreciated in terms of how the final string retuned from the function is 'olleh'
推荐答案
这是递归调用的顺序,以及它们返回的内容。你会看到 reverse(hello)
返回 reverse(ello)
加上<$的结果C $ C> H。
Here's the sequence of recursive calls, and what they return. You'll see that reverse("hello")
returns the result of reverse("ello")
plus "h"
.
reverse("hello")
--> return reverse("ello") + "h"
那么问题是 reverse(ello)
return?
So then the question is what does reverse("ello")
return?
reverse("ello")
--> return reverse("llo") + "e"
继续...
reverse("llo")
--> return reverse("lo") + "l"
reverse("lo")
--> return reverse("o") + "l"
最后,当<$ c $调用c> reverse(o)。这里 len(text)<= 1
,所以它只返回o
。
Finally, it bottoms out when reverse("o")
is called. Here len(text) <= 1
, and so it returns simply "o"
.
reverse("o")
--> return "o"
然后,您可以按照自下而上的方式返回以计算返回值从原来的 reverse(hello)
调用。
You can then work your way back up from bottom to top to calculate the return value from the original reverse("hello")
call.
这篇关于理解递归字符串反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!