How to change a string using recursion?

I am trying a simple program that would allow me to print the opposite word "computer". When I run my code, I got a RuntimeError runtime error: maximum recursion depth exceeded in cmp.

Can I find out what happened and how can I solve it?

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

print reverse('retupmoc')
+4
source share
2 answers

The problem is here

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

You combine the rest of the string with the first character and move on to the function reverse. Thus, the length of the string never decreases.

It should be

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

, reverse. , .

+7

python , .

: s[::-1], s - , .

+1

Source: https://habr.com/ru/post/1618125/


All Articles