Ashref Ashref - 1 year ago 94
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 ''
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 Source

Check this:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download