如何使用递归编写相同的函数?
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"""
我相信我应该制作原件的副本,然后从那里制作一个列表中的a = b,但我不知道如何实现它。请帮我解决这个问题,谢谢!
答案 0 :(得分:0)
试试这个:
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)
它是一种递归解决方案,并按预期工作:
replace([1, 2, 3, 1], 1, 4)
=> [4, 2, 3, 4]