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?
1 Answer 1
Your answer is correct, but the exercise probably wanted to reveal other concepts such as for loops and string concatenation using + and +=.
That said, I'd like to add to the stated solution that it is a better practice to use an underscore when you don't really need the loop variable. It's a way of telling future programmers you are not using the variable anywhere in the loop.
It's also better to use xrange if you don't actually need a list (generated by range). You can try in the interpreter range(1000000) and xrange(1000000) to see the immediate difference. xrange is actually a generator, making it a lot more memory efficient.
in python 3, range returns a generator by default
# changed i to an underscore, using xrange instead of range
for _ in xrange(n): # xrange(n) *generates* 0, 1, 2 ... n-1
2 Comments
range and xrange, I think that your hint applyes only to Python 2.x, in later versions range is deleted and xrange is renamed to range.
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.