给定一个字符串列表,我需要通过组合所有字符串的第一个字符来生成一个新字符串。我的解决方案:
def K(lst):
if lst == []:
return ""
else:
return lst[0][0] + K(lst[1:])
它有效,但我确信这不是累积递归。 我也尝试过使用累积递归来尝试这道题,但找不到正确的解决方案。
def K(lst):
acc = ""
if lst == []:
return acc
else:
acc = acc + lst[0][0]
return K(lst[1:])
我不知道如何改变 acc
。
最佳答案
您不能在递归函数内声明累加器,因为每次调用都会重新定义它。您需要将其作为函数的参数,常见的习惯用法是创建一个在其定义中包含累加器的辅助函数:
def K(lst):
return _K(lst, [])
def _K(lst, acc):
if lst == []:
return acc
else:
head, tail = lst[0], lst[1:]
return _K(tail, acc + head[0])
关于python - 累积递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27328633/