Answer on Question #62199, Programming & Computer Science / Python
You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.
Solution:
Iterative function using while loop:
def replicate_iter(n, dat):
answer = ""
k = 0
while k < n:
answer = answer + str(dat)
k += 1
return answerExamples:
print(replicate_iter(5, 6))
print(replicate_iter(2, "123abcd"))
66666
123abcd 123abcdRecursive function (calls itself):
def replicate_recur(n, dat):
if n <= 0:
return ""
else:
return replicate_recur(n - 1, dat) + str(dat)Examples:
print(replicate_recur(5, 6))
print(replicate_recur(2, "abcd123"))
66666
abcd123 abcd123Screenshot of both functions:
1 def replicate_iter(n, dat):
2 answer = ""
3 k = 0
4 while k < n:
5 answer = answer + str(dat)
6 k += 1
7 return answer
8
9 def replicate_recur(n, dat):
10 if n <= 0:
11 return ""
12 else:
13 return replicate_recur(n - 1, dat) + str(dat)http://www.AssignmentExpert.com
Comments