4

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')
2
  • 2
    Other than a programming exercise, I assume you are aware of this way of reversing a string: 'retupmoc'[::-1] Commented Dec 1, 2015 at 14:52
  • 1
    You can also reduce the code to return reverse(str1[1:]) + str1[0] if str1 else "" Commented Dec 1, 2015 at 15:11

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

This seems more like a comment than an answer itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.