Ashref Ashref - 1 month ago 14
Python Question

Recursive functions : Inversing word

I'm trying to make a simple function that inverses a string using recursion.

this is what i tried :

def inverse(ch):
if ch=='' :
return ''
else:
return ch[len(ch)]+inverse(ch[1:len(ch)-1])

print inverse('hello')


And this is what i get :


line 13, in inverse
return ch[len(ch)]+inverse(ch[1:len(ch)-1]) IndexError: string index out of range

Answer

Check this:

ch[len(ch)-1]+inverse(ch[0:len(ch)-1]) 
Comments