简体   繁体   中英

How to reverse a string using recursion?

I'm trying out a simple program which would allow me to print out the reverse word of "computer". When I run my code, I received a runtime error RuntimeError: maximum recursion depth exceeded in cmp .

May I know what had happen and how can I solve it?

def reverse(str1):
    if str1 == '':
        return str1
    else:
        return reverse(str1[1:] + str1[0])

print reverse('retupmoc')

The problem is here,

return reverse(str1[1:] + str1[0])

You are concatenating the rest of the string with the first character and passing to the reverse function. So, the length of the string never reduces.

It should have been

return reverse(str1[1:]) + str1[0]

Now, you are passing only the rest of the string, excluding the first character to the recursive reverse function. So, on each recursive level, one character will be removed from the string and it will eventually meet your base condition.

In python, you can reverse strings in one simple line, and avoid recursive entirely, unless it is some assignment with a requirement.

So do: s[::-1] , where s is the variable name of the string to be reversed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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