Recursive functions : Inversing word
<p>I'm trying to make a simple function that inverses a string using recursion.</p>

<p>this is what i tried : </p>

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

    print inverse('hello')
</code></pre>

<p>And this is what i get : </p>

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

<p>You're indexing the string at its length, but remember that indexing is zero based so you'll have to slice at length minus 1 which is the maximum index you can safely use.</p>

<p>You can however choose to be oblivious of the length by using <code>[-1]</code> to index the last item:</p>

<pre><code>def inverse(ch):
    if ch=='' :
        return ''
    else:
        return ch[-1]+inverse(ch[:-1])

print inverse('hello')
# olleh
</code></pre>

<p>And you also probably want to keep in mind that slicing with <code>[::-1]</code> provides the same result as your recursive function.</p>

python recursion