I'm very new and just came across an exercise which asks:
Given a string and a non-negative integer
n, return a larger string that isncopies of the original string.
I answered:
def string_times(str, n):
return(str * n)
and passed all tests. The solution provided:
def string_times(str, n):
result = ""
for i in range(n): # range(n) is [0, 1, 2, .... n-1]
result = result + str # could use += here
return result
My question is: is there any reason why my simpler solution won't work in some cases, or is it just a matter of a more experienced programmer overthinking things?
str, but I guess you were provided with the function definition.forloop and is much easier to expand, e.g. other delimiters between the copies. Your solution is clean for the purpose but hides the functionality a bit.stras a variable name prevents you from accessing the built-in type.