Python 使用递归反转字符串

发布于 2024-10-30 13:52:33 字数 433 浏览 0 评论 0原文

我想使用递归来反转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 技术交流群。

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

发布评论

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

评论(8

盛夏已如深秋| 2024-11-06 13:52:33
def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

(很少有人在 Python 中进行繁重的递归处理,该语言不是为此设计的.)

def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)

静若繁花 2024-11-06 13:52:33

要递归地解决问题,请找到一个易于解决的简单案例,并通过将问题分解为越来越简单的版本来找出如何解决该简单案例。

反转字符串时要做的第一件事是什么?从字面上看是第一件事吗?你得到了字符串的最后一个字符,对吗?

因此,字符串的反转是最后一个字符,后面是除最后一个字符之外的所有内容的反转,这就是递归的用武之地。字符串的最后一个字符可以写为 x[-1] 而除了最后一个字符之外的所有内容都是 x[:-1]

现在,如何“走出低谷”?也就是说,无需递归即可解决的简单情况是什么?一种答案是单字符串,正反都是一样的。因此,如果你得到一个单字符字符串,那么你就完成了。

但是空字符串更加微不足道,并且有人可能实际上将其传递给您的函数,因此我们可能应该使用它。毕竟,单字符字符串也可以分解为最后一个字符以及除最后一个字符以外的所有字符;只是除了最后一个字符之外的所有内容都是空字符串。因此,如果我们通过返回空字符串来处理它,那么我们就完成了。

把它们放在一起,你会得到:

def backward(text):
    if text == "":
        return text
    else:
        return text[-1] + backward(text[:-1])

或者在一行中:

backward = lambda t: t[-1] + backward(t[:-1]) if t else t

正如其他人所指出的,这不是你通常在 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 is x[:-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:

def backward(text):
    if text == "":
        return text
    else:
        return text[-1] + backward(text[:-1])

Or in one line:

backward = lambda t: t[-1] + backward(t[:-1]) if t else t

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.

孤星 2024-11-06 13:52:33

我只想根据 Fred Foo 的回答添加一些解释。
假设我们有一个名为“abc”的字符串,我们想要返回其相反的字符串,即“cba”。

def reverse(s):
    if s == "":
        return s
    else:
        return reverse(s[1:]) + s[0]
   
             
s = "abc"
print (reverse(s)) 

这段代码的工作原理是:
当我们调用该函数时

reverse('abc')                       #s = abc
=reverse('bc') + 'a'                 #s[1:] = bc    s[0] = a
=reverse('c') + 'b' + 'a'            #s[1:] = c     s[0] = a
=reverse('') + 'c' + 'b' + 'a'
='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'.

def reverse(s):
    if s == "":
        return s
    else:
        return reverse(s[1:]) + s[0]
   
             
s = "abc"
print (reverse(s)) 

How this code works is that:
when we call the function

reverse('abc')                       #s = abc
=reverse('bc') + 'a'                 #s[1:] = bc    s[0] = a
=reverse('c') + 'b' + 'a'            #s[1:] = c     s[0] = a
=reverse('') + 'c' + 'b' + 'a'
='cba'
挽清梦 2024-11-06 13:52:33

如果这不仅仅是一个家庭作业问题,并且您实际上是为了某个更大的目标而尝试反转字符串,那么只需执行 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].

⒈起吃苦の倖褔 2024-11-06 13:52:33
def reverse_string(s):
    if s: return s[-1] + reverse_string(s[0:-1])
    else: return s

或者

def reverse_string(s):
    return s[-1] + reverse_string(s[0:-1]) if s else s
def reverse_string(s):
    if s: return s[-1] + reverse_string(s[0:-1])
    else: return s

or

def reverse_string(s):
    return s[-1] + reverse_string(s[0:-1]) if s else s
坠似风落 2024-11-06 13:52:33

我知道现在回答原来的问题已经太晚了,这里已经回答了多种更好的方法。我的答案是出于文档目的,以防有人试图实现字符串反转的尾递归。

def tail_rev(in_string,rev_string):
    if in_string=='':
        return rev_string
    else:
        rev_string+=in_string[-1]
        return tail_rev(in_string[:-1],rev_string)
    
in_string=input("Enter String: ")
rev_string=tail_rev(in_string,'')
print(f"Reverse of {in_string} is {rev_string}") 

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.

def tail_rev(in_string,rev_string):
    if in_string=='':
        return rev_string
    else:
        rev_string+=in_string[-1]
        return tail_rev(in_string[:-1],rev_string)
    
in_string=input("Enter String: ")
rev_string=tail_rev(in_string,'')
print(f"Reverse of {in_string} is {rev_string}") 
慈悲佛祖 2024-11-06 13:52:33

如果您不想返回响应,可以使用此解决方案。这个问题是 LeetCode 的一部分。

class Solution:
    i = 0
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        if self.i >= (len(s)//2):
            return
        s[self.i], s[len(s)-self.i-1] = s[len(s)-self.i-1], s[self.i]
        self.i += 1
        self.reverseString(s)

if you do not want to return response than you can use this solution. This question is part of LeetCode.

class Solution:
    i = 0
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        if self.i >= (len(s)//2):
            return
        s[self.i], s[len(s)-self.i-1] = s[len(s)-self.i-1], s[self.i]
        self.i += 1
        self.reverseString(s)
怪我闹别瞎闹 2024-11-06 13:52:33
s = input("Enter your string: ")

def rev(s):
    if len(s) == 1:
        print(s[0])
        exit()
    else:
        #print the last char in string
        #end="" prints all chars in string on same line
        print(s[-1], end="")
        """Next line replaces whole string with same
         string, but with 1 char less"""
        return rev(s.replace(s, s[:-1]))

rev(s)
s = input("Enter your string: ")

def rev(s):
    if len(s) == 1:
        print(s[0])
        exit()
    else:
        #print the last char in string
        #end="" prints all chars in string on same line
        print(s[-1], end="")
        """Next line replaces whole string with same
         string, but with 1 char less"""
        return rev(s.replace(s, s[:-1]))

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