Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 982
stack Avatar asked Feb 08 '23 10:02

stack


1 Answers

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.

like image 136
thefourtheye Avatar answered Feb 11 '23 03:02

thefourtheye