mardi 17 mars 2015

repeating a string using a multiplier vs range()


Vote count:

0




The following is the question I'm presented:



Given a string and a non-negative int n, return a larger string that is n copies of the original string.


string_times('Hi', 2) → 'HiHi'


string_times('Hi', 3) → 'HiHiHi'


string_times('Hi', 1) → 'Hi'



my solution for this is:



def string_times(str, n):

if str and n >= 0:
return str*n


the result came back as:



Expected Run
string_times('Hi', 2) → 'HiHi'
string_times('Hi', 3) → 'HiHiHi'
string_times('Hi', 1) → 'Hi'
string_times('Hi', 0) → ''
string_times('Hi', 5) → 'HiHiHiHiHi'
string_times('Oh Boy!', 2) → 'Oh Boy!Oh Boy!'
string_times('x', 4) → 'xxxx'

string_times('', 4) → '' None X <-- issue

string_times('code', 2) → 'codecode'
string_times('code', 3) → 'codecodecode'


From what I can see, I'm missing the "null" part of the equation.


The solution given is the following:



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, in my solution does the fact that nothing*4 give nothing?


Also, can you please explain how using the built in range() function would be a more elegant solution?


Thanks in advance



asked 33 secs ago







repeating a string using a multiplier vs range()

Aucun commentaire:

Enregistrer un commentaire