-3
def strings_in_a_list(n, s):
    """
    ----------------------------
    Creates a Python list with a string, s, repeated n times. Uses recursion.
    Use: list = strings_in_a_list (n, s)
    -----------------------------
    Preconditions:
        n - a nonnegative integer (int)
        s - a string (str)
    Postconditions:   
        returns
        l - a list with n copies of the string s (list of string)
    -----------------------------
    """
    l = [] 
    l.append(s)
    if len(l) != n:
        l = l * n
    return l

Would this be an acceptable recursive function, if no would you be able to show me a better and proper way of doing this? Thanks in advance.

output should be like this example:
strings_in_a_list(3, 'Dream') should return the list ['Dream', 'Dream', 'Dream']

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
James D
  • 13
  • 3
  • Would it be much better if you can make your program more readable. Add 4 space at the beginning of each line. – Hun Feb 27 '16 at 22:39
  • Does this answer your question? [Understanding recursion](https://stackoverflow.com/questions/717725/understanding-recursion) – Karl Knechtel Oct 06 '22 at 06:22
  • To be an acceptable recursive function, it would have to be recursive. To answer a question like this, the first step is to learn what that means. For example, by using a dictionary or a search engine. – Karl Knechtel Oct 06 '22 at 06:22

1 Answers1

2

A recursive function should be calling itself and takes the general form of the following at the bare minimum, will change depending on what you're trying to do.

if (terminate condition):
    return (final value)
else:
    return function( x - 1 )

This will do what you want. The terminate condition is when n equals 0, in which an empty list is returned. Otherwise l equals the result of the function call and s is appended before being returned.

def strings_in_a_list(n, s):
    if n == 0:
        return []
    else:
        l = strings_in_a_list(n - 1, s)
        l.append(s)
        return l
Steven Summers
  • 5,079
  • 2
  • 20
  • 31
  • You can avoid `O(N**2)` running time if you `append` to the list returned by the recusive call, rather than doing a string concatenation: `L = string_in_a_list(n-1, s); L.append(s); return L` – Blckknght Feb 27 '16 at 23:49
  • Thanks, I was just in the middle of testing that and about to update. Since the OP question uses a list, I figured it would be better to provide the answer using a list. – Steven Summers Feb 27 '16 at 23:51
  • Thank you very much, this is really helpful – James D Feb 28 '16 at 00:10