Sulayman A.

asked • 09/15/16

Recursion lab


RECURSION LAB
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) orreplicate_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.
TEST QUESTION:4
import unittest

class ReplicateIterTestCases(unittest.TestCase):
def test_it_returns_a_list_of_replicated_numbers(self):
result = replicate_iter(3, 5)
self.assertEqual(result, [5, 5, 5], msg='It should produce a list of three fives for the input 3, 5')

def test_it_returns_an_empty_list_for_0_times(self):
result = replicate_iter(0, 5)
self.assertEqual(result,[], msg='It should return an empty list if times == 0')

def test_it_returns_an_empty_list_for_negative_times(self):
result = replicate_iter(-1, 20)
self.assertEqual(result, [], msg='It should return an empty list for negative times.')

def test_it_raises_value_error_if_invalid_input(self):
with self.assertRaises(ValueError):
replicate_iter(1, [])

def test_it_raises_value_error_if_invalid_number_of_times_to_repeat(self):
with self.assertRaises(ValueError):
replicate_iter([], 3)

def test_it_can_repeat_strings(self):
result = replicate_iter(3, 'str')
self.assertEqual(result, ['str', 'str', 'str'], msg='Should replicate strings too')

class ReplicateRecurTestCases(unittest.TestCase):
def test_it_returns_a_list_of_replicated_numbers(self):
result = replicate_recur(4, 5)
self.assertEqual(result, [5, 5, 5, 5], msg='It should produce a list of four fives for the input 4, 5')

def test_it_returns_an_empty_list_for_0_times(self):
result = replicate_recur(0, 5)
self.assertEqual(result,[], msg='It should return an empty list if times == 0')

def test_it_returns_an_empty_list_for_negative_times(self):
result = replicate_recur(-1, 20)
self.assertEqual(result, [], msg='It should return an empty list for negative times.')

def test_it_raises_value_error_if_invalid_input(self):
with self.assertRaises(ValueError):
replicate_recur(1, [])

def test_it_raises_value_error_if_invalid_number_of_times_to_repeat(self):
with self.assertRaises(ValueError):
replicate_recur([], 3)

1 Expert Answer

By:

Patrick B. answered • 05/03/20

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.