VERY basic python string

I am very new and just stumbled upon an exercise that asks:

If given a string and a non-negative integer n

, return a large string that is n

copies of the original string.

I answered:

def string_times(str, n):
    return(str * n)

      

and passed all tests. 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 a reason why my simpler solution won't work in some cases, or is it just a matter of a more experienced programmer overdoing it?

+3


source to share


1 answer


Your answer is correct, but the exercise probably wanted to identify other concepts, such as for loops and string concatenation with +

and +=

.

However, I would like to add to the stated solution that it is better to use an underscore when you don't need a loop variable. This is a way to tell future programmers that you are not using a variable anywhere in the loop.

It's also better to use xrange unless you really want the list (generated by the range). You can try the interpreter range(1000000)

and xrange(1000000)

to see the immediate difference. xrange

is actually a generator , which makes it much more memory efficient.



in python 3, range returns the default generator

# changed i to an underscore, using xrange instead of range
for _ in xrange(n):  # xrange(n) *generates* 0, 1, 2 ... n-1

      

+1


source







All Articles