How to write a recursive function to print a string a certain number of times?
<p>I have been trying to write a python function which will receive two arguments: <code>x</code> which is the number of times to repeat and <code>y</code> which is the number or string to be repeated.</p>

<p>So far this is what I have been able to come up with, but I can't seem to be able to determine how to do it recursively.</p>

<pre><code>def recurse(x, y):
    final = []
    if x == 0:
        return ("")
    else:
        x = x - 1
        final.append(recurse(x,y))              
    return final
</code></pre>

<p>If <code>recurse(3,"Cat")</code> is called, the output is meant to look like this:</p>

<pre><code>print recurse(3, 'cat')
['cat','cat','cat']
</code></pre>

<p>How would I go about doing this?</p>

<p>True functional recursion should have <em>no</em> assignments (i.e. state).
This can be achieved using what's called an <em>accumulator</em>, i.e. an array that is built up successively and passed to each recursive step, until the base case occurs, causing the accumulator's final form to be returned directely, and indirectly <em>all the way back</em> to the initial calling instance.</p>

<pre><code>&gt;&gt;&gt; def recurse(Iters, text, Accumulator=[]):
...   if Iters == 0: return Accumulator                   # base case
...   return recurse(Iters-1, text, Accumulator + [text]) # recursive step
... 
&gt;&gt;&gt; recurse(3, 'helle')
['helle', 'helle', 'helle']
</code></pre>

<p>Note that there is no change of <em>state</em> at any point; all "updates" occur at the point of calling the next recursive step with updated arguments.</p>

python recursion