0

How can I write this same function using recursion?

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

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

Precondition: thelist is a list of ints
              a and b are ints"""

I believe I'm supposed to make a copy of the original, and then from there make a = b in the list, but I do not know how to implement that. Please help me solve this, and thank you!

AdamMc331
  • 16,492
  • 10
  • 71
  • 133
steve12
  • 3
  • 1
  • 2

1 Answers1

0

Try this:

def replace(thelist, a, b):
    if not thelist:
        return []
    elif thelist[0] == a:
        return [b] + replace(thelist[1:], a, b)
    else:
        return [thelist[0]] + replace(thelist[1:], a, b)

It's a recursive solution, and works as expected:

replace([1, 2, 3, 1], 1, 4)
=> [4, 2, 3, 4]
Óscar López
  • 232,561
  • 37
  • 312
  • 386