简体   繁体   English

Python 使用递归反转字符串,解释

[英]Python Reverse a string using recursion, explanation

I need to reverse a string using recursion, I was able to accidentally write a code that successfully accomplishes the task, but I don't really understand why.我需要使用递归来反转字符串,我不小心编写了成功完成任务的代码,但我真的不明白为什么。 Here's what I have这就是我所拥有的

import stdio
import sys


# Entry point
def main():
    s = sys.argv[1]
    stdio.writeln(_reverse(s))


# Returns the reverse of the string s.
def _reverse(s):
    # Base case: if s is the empty string, return an empty string.
    if len(s) == 0:
        return ""
    # Recursive step: return last character in s + _reverse(s excluding last character).
    else:
        return s[-1] + _reverse(s[:len(s)-1]) 


if __name__ == '__main__':
    main() 

This makes sense to me just for the first recursive call.仅对于第一次递归调用,这对我来说很有意义。 Lets say the input is "Bolton" the length of this string is 6, the first recursive call would simply call the _reverse function on s [0:5] What I don't understand is that how do the next recursive calls work?假设输入是“Bolton”,这个字符串的长度是 6,第一个递归调用将简单地在 s [0:5] 上调用 _reverse function 我不明白的是下一个递归调用是如何工作的? Because len(s) would remain the same?因为 len(s) 会保持不变? To my understanding, each recursive call to the _reverse() would subtract 1 from len(s) -- which is 6. Can someone please explain why thats not the case?据我了解,每次对 _reverse() 的递归调用都会从 len(s) 中减去 1——即 6。有人可以解释为什么不是这样吗? How does the the len decrement? len如何递减?

s[:len(s)-1] or the same value but shorter s[:-1] is essentially a string with the last element removed, the length of it is 1 shorter than the original. s[:len(s)-1]或相同值但更短s[:-1]本质上是一个字符串,删除了最后一个元素,它的长度比原来的短 1。 You then call the function with that shorter string.然后,您使用该较短的字符串调用 function。

So a step by step resolution would look something like this:所以一步一步的解决方案看起来像这样:

reverse("hello") # len("hello") != 0 so we substitute with else
"hello"[-1] + reverse("hello"[:-1])
"o" + reverse("hell")
"o" + "hell"[-1] + reverse("hell"[:-1])
"o" + "l" + reverse("hel")
"o" + "l" + "hel"[-1] + reverse("hel"[:-1])
"o" + "l" + "l" + reverse("he")
"o" + "l" + "l" + "he"[-1] + reverse("he"[:-1])
"o" + "l" + "l" + "e" + reverse("h")
"o" + "l" + "l" + "e" + "h"[-1] + reverse("h"[:-1])
"o" + "l" + "l" + "e" + "h" + reverse("") # len("") == 0 so we substitute ""
"o" + "l" + "l" + "e" + "h" + ""
"olleh"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM