Question #62195

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.

Expert's answer

Answer on Question #62195 - Programming & Computer Science - Python

-*- 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 None
    if a == 1:
        return b
    res = replicate_recur(a - 1, b)
    res += 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
    # exit from function
    if a <= 0:
        return None
    res = b
    for i in range(1, a):
        res += b
    return res
a, b = (3, "a")
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

LATEST TUTORIALS
APPROVED BY CLIENTS