Question #62199

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.
1

Expert's answer

2016-09-22T11:59:04-0400

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 answer


Examples:


print(replicate_iter(5, 6))
print(replicate_iter(2, "123abcd"))
66666
123abcd 123abcd


Recursive 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 abcd123


Screenshot 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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS