Question #62041

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.

The function should return an array containing repetitions of the data argument. For instance, replicate_recur(3, 5) or replicate_iter(3,5) should return [5,5,5]. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a ValueError.
1

Expert's answer

2016-09-16T09:23:03-0400

Answer on Question #62041 – 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.

The function should return an array containing repetitions of the data argument. For instance, replicate_recur(3, 5) or replicate_iter(3,5) should return [5,5,5]. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a ValueError.


# -*- coding: utf-8 -*-
#recursive function
def replicate_recur(a, b):
    #checking for correctness of 'a' type
    if not isinstance(a, int):
        raise ValueError
    #exit from function
    if a <= 0:
        return []
    res = replicate_recur(a - 1, b)
    res.append(b)
    #returning of result
    return res
#iterative function
def replicate_iter(a, b):
    #checking for correctness of 'a' type
    if not isinstance(a, int):
        raise ValueError
    res = []
    for i in range(a):
        res.append(b)
    return res
a, b = (3, 5)
try:
    print(replicate_recur(a, b))
except ValueError:
    print("Wrong 'a' type")
try:
    print(replicate_iter(a, b))
except ValueError:
    print("Wrong 'a' type")
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