Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete the following function using recursion: def replace(thelist,a,b): \"\"\

ID: 3825424 • Letter: C

Question

Complete the following function using recursion:

def replace(thelist,a,b):
"""Returns: a COPY of thelist but with all occurrences of int a replaced by
int b. Does not change thelist.

Example: replace([1,2,3,1], 1, 4) = [4,2,3,4].

Precondition: thelist is a possibly empty list of ints."""

You may use the following test cases to verify your answer:

test_cases = {
((5, 6), 5, 4): [4, 6],
((5, 6), 6, 4): [5, 4],
((5, 5), 5, -4): [-4, -4],
((), 1, 2): [],
((5, 3, 3455, 74, 74, 74, 3), 3, 20): [5, 20, 3455, 74, 74, 74, 20],
((5, 3, 3455, 74, 74, 74, 3), 1, 20): [5, 3, 3455, 74, 74, 74, 3],
}

Explanation / Answer

##Recursive function

def replace(thelist,a,b):

if len(thelist)==0:

return

else:

if thelist[0]==a:

thelist[0]=b

return replace(thelist[1:],a,b)

thelist=[1,2,3,4] ##Input

replace(thelist,1,4)

print(thelist) ##Prints output