Python Recursion vs Iteration
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>

<blockquote>
  <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p>
</blockquote>

<p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p>

<p>Now here is my code:</p>

<pre><code>my_list1 = []
my_list2 = []
   def replicate_iter(times,data):
      try:
        if type(data) != int and type(data) != str:
          raise ValueError('Invalid Argument')
        times += 0
          if times &gt; 0:
            x = 0
            while x &lt; times:
            my_list2.append(data)
            x = x+1
           return my_list2
         else:
          return []
    except (ValueError,AttributeError,TypeError):
        raise ValueError('Invalid Argument')

def replicate_recur(times,data):
    try:
        if type(data) != int and type(data) != str:
          raise ValueError('Invalid Argument')
        times += 0
        if times &lt;= 0:
          return my_list1
        else:
          my_list1.append(data)
          return replicate_recur(times-1,data)
    except(AttributeError,TypeError):
        raise ValueError('Invalid Argument')
</code></pre>

<p>I think the iterative version is straightforward, and others have provided good answers.  As for the recursion, I always like to see if I can come up with a divide and conquer strategy rather than whittle the problem down one step at a time, to avoid blowing out the stack.  The following does that:</p>

<pre><code>def replicate_recur(times, data):
    def f(n, value):
        if n &lt; 1:
            return [] 
        result = f(n // 2, value) * 2
        if n % 2 &gt; 0:
            result += [value] 
        return result

    if not isinstance(data, int) and not isinstance(data, str):
        raise ValueError('Must be int or str')
    return f(times, data)
</code></pre>

<p>This uses an internal recursive function <code>f()</code> to avoid repeating the type checking for <code>data</code>. The recursion constructs a list of half the size, and either doubles it (if the current <code>n</code> is even) or doubles it and adds one more occurrence of <code>data</code> (if the current <code>n</code> is odd).</p>

<p>Try it, you'll like it!</p>

python recursion iteration