繁体   English   中英

是否可以使用递归来使用 Python 查找数组的每个元素的总和?

[英]Is is possible to use recursion to find the sum of each elements of an array using Python?

我在使用递归添加数组的每个元素并生成另一个包含它们总和的列表时遇到问题。

def add(l1,l2,n,counter): # define new user function named add
    if c >= n: # base case
        # if counter is now greater than the length of the list then return empty array
        return []
    return l1[c] + l2[c], add(l1,l2,n,c+1) # recursion

list1 = [7,8,9] # list 1
list2 = [10,11,12] # list 2
print(add(list1,list2,3,0)) # prompt the output of the add() function

在这种情况下, add() 函数的函数应该返回一个值为[17,19,21]的列表。 相反,它返回一个值为(17, (19, (21, [ ]))) 的元组

有人可以告诉我我可以在代码中改进什么吗? 我感谢您提供的任何帮助。

首先,这个问题根本不需要递归。 但考虑到这是你的问题,你可以做的是你可以返回一个列表而不是一个元组。 所以而不是这个

return l1[c] + l2[c], add(l1,l2,n,c+1) # recursion

你可以退回这个

return [l1[c] + l2[c], add(l1,l2,n,c+1)] # recursion

但这会给你 [17, [19, [21, []]]] 作为结果,因为在每次递归时你都会返回一个列表。

为了克服这个问题,您应该在每次迭代时传播返回的列表。 最终代码如下所示:

return [l1[c] + l2[c], *add(l1,l2,n,c+1)] # recursion

* 运算符展开返回的列表,结果您得到一个列表。

我个人会像下面这样写,这不关心列表的长度,甚至允许一个列表比另一个长等等。它检查两个列表是否为空,如果是,则返回一个空列表,否则它从每个列表中获取第一个值,如果列表没有更多值,则默认为 0。 然后使用每个列表中的剩余值再次调用该函数。 等等。

def add(l1, l2):  # define new user function named add
    if len(l1) == 0 and len(l2) == 0:
        return []

    n1 = l1[0] if l1 else 0
    n2 = l2[0] if l2 else 0
    t = n1 + n2
    return [t] + add(l1[1:], l2[1:])  # recursion


list1 = [7, 8, 9, 50]  # list 1
list2 = [10, 11, 12]  # list 2
print(add(list1, list2))

输出

[17, 19, 21, 50]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM