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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With