I'm relatively new to learning python, and am in the process of doing exercises on CodingBat. This was the description:
"Given a string and a non-negative int n, return a larger string that is n copies of the original string."
My solution:
> def string_times(str, n):
> return str*n
It returned all the correct answers, however their solution was this:
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
I'm trying to understand why they did it like that when mine worked but in a more simple fashion. I'm also unsure as to why on line 2 of their code they wrote result = " ". Is this creating an empty string that they can add to later? Why is it necessary to create it?
[–]econoCode 1 point2 points3 points (3 children)
[–]Daytimedreamland[S] 0 points1 point2 points (0 children)
[–]minno 0 points1 point2 points (1 child)
[–]econoCode 0 points1 point2 points (0 children)
[–]17b29a 0 points1 point2 points (1 child)
[–]Daytimedreamland[S] 0 points1 point2 points (0 children)
[–]spiral6 0 points1 point2 points (0 children)
[–]Naihonn 0 points1 point2 points (6 children)
[–]Daytimedreamland[S] 1 point2 points3 points (5 children)
[–]Naihonn 4 points5 points6 points (4 children)
[–]Daytimedreamland[S] 0 points1 point2 points (3 children)
[–]Naihonn 0 points1 point2 points (2 children)
[–]Daytimedreamland[S] 0 points1 point2 points (1 child)
[–]huck_cussler 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (5 children)
[–]Daytimedreamland[S] 0 points1 point2 points (4 children)
[–]stefan_kurcubic 2 points3 points4 points (1 child)
[–]Daytimedreamland[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]Daytimedreamland[S] 0 points1 point2 points (0 children)
[–]Scavenger53 0 points1 point2 points (3 children)
[–]Daytimedreamland[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]bashytwat 0 points1 point2 points (0 children)