Python 使用递归反转字符串
我想使用递归来反转Python中的字符串,以便它向后显示字符(即“Hello”将变成“olleh”/“olle h”。
我写了一个迭代执行此操作的程序:
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
n = n + 1
result = s[ start: n ] + " " + result
start = n
return result
但是我到底如何递归地执行此操作?我对这部分感到困惑,特别是因为我不太使用 python 和递归,
任何帮助将不胜感激。
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
n = n + 1
result = s[ start: n ] + " " + result
start = n
return result
But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much.
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
(很少有人在 Python 中进行繁重的递归处理,该语言不是为此设计的.)
(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)
要递归地解决问题,请找到一个易于解决的简单案例,并通过将问题分解为越来越简单的版本来找出如何解决该简单案例。
反转字符串时要做的第一件事是什么?从字面上看是第一件事吗?你得到了字符串的最后一个字符,对吗?
因此,字符串的反转是最后一个字符,后面是除最后一个字符之外的所有内容的反转,这就是递归的用武之地。字符串的最后一个字符可以写为
x[-1]
而除了最后一个字符之外的所有内容都是x[:-1]
。现在,如何“走出低谷”?也就是说,无需递归即可解决的简单情况是什么?一种答案是单字符串,正反都是一样的。因此,如果你得到一个单字符字符串,那么你就完成了。
但是空字符串更加微不足道,并且有人可能实际上将其传递给您的函数,因此我们可能应该使用它。毕竟,单字符字符串也可以分解为最后一个字符以及除最后一个字符以外的所有字符;只是除了最后一个字符之外的所有内容都是空字符串。因此,如果我们通过返回空字符串来处理它,那么我们就完成了。
把它们放在一起,你会得到:
或者在一行中:
正如其他人所指出的,这不是你通常在 Python 中执行此操作的方式。迭代解决方案将会更快,并且使用切片来完成它也会更快。
此外,Python 对堆栈大小施加了限制,并且没有尾部调用优化,因此递归解决方案仅限于反转大约一千个字符的字符串。您可以增加Python的堆栈大小,但仍然有固定的限制,而其他解决方案始终可以处理任何长度的字符串。
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right?
So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as
x[-1]
while everything but the last character isx[:-1]
.Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done.
But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, also be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set.
Put it all together and you get:
Or in one line:
As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still.
Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
我只想根据 Fred Foo 的回答添加一些解释。
假设我们有一个名为“abc”的字符串,我们想要返回其相反的字符串,即“cba”。
这段代码的工作原理是:
当我们调用该函数时
I just want to add some explanations based on Fred Foo's answer.
Let's say we have a string called 'abc', and we want to return its reverse which should be 'cba'.
How this code works is that:
when we call the function
如果这不仅仅是一个家庭作业问题,并且您实际上是为了某个更大的目标而尝试反转字符串,那么只需执行
s[::-1]
即可。If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do
s[::-1]
.或者
or
我知道现在回答原来的问题已经太晚了,这里已经回答了多种更好的方法。我的答案是出于文档目的,以防有人试图实现字符串反转的尾递归。
I know it's too late to answer original question and there are multiple better ways which are answered here already. My answer is for documentation purpose in case someone is trying to implement tail recursion for string reversal.
如果您不想返回响应,可以使用此解决方案。这个问题是 LeetCode 的一部分。
if you do not want to return response than you can use this solution. This question is part of LeetCode.