stack
stack

Reputation: 414

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')

Upvotes: 4

Views: 2218

Answers (2)

m_callens
m_callens

Reputation: 6360

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.

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239443

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.

Upvotes: 7

Related Questions