Reputation: 31
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 isn
copies 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?
Upvotes: 3
Views: 185
Reputation: 31339
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
Upvotes: 1