Home > katas > String repeat (8kyu) [Python]
String repeat (8kyu) [Python]
Chek kata on Codewars
Description:
Write a function called repeat_str which repeats the given string src exactly count times.
repeatStr(6, "I") // "IIIIII"
repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"
Solution 1.1
Let's start with a loop
solution.
def repeat_str(repeat, string):
new_str = ''
while repeat > 0:
new_str += string
repeat -= 1
return new_str
Solution 1.2
def repeat_str(repeat, string):
new_str = ''
for _ in range(repeat):
new_str += string
return new_str
Solution 1.3
We can add an array to this for loop.
def repeat_str(repeat, string):
new_str = []
for _ in range(repeat):
new_str.append(string)
return "".join(new_str)
Solution 2.1
def repeat_str(repeat, string):
return string * repeat
Solution 3.1
Let's solve it recursively.
def repeat_str(repeat, string):
return string if repeat == 1 else string + repeat_str(repeat - 1, string)