【问题标题】:How can I make a recursive function that returns a list of sum of the same index given two lists.?如何创建一个递归函数,返回给定两个列表的相同索引的总和列表。?
【发布时间】:2021-10-30 10:39:47
【问题描述】:

如何创建一个递归函数,返回给定两个列表的相同索引的总和列表。?

我只想让它成为一个递归函数。

例如:

list1 = [1,2,3]
list2 = [2,4,6]

递归函数将返回一个新列表 [3,6,9]

语言也应该是python。

谢谢。我只是很难弄清楚。

【问题讨论】:

  • 它必须是递归的?以非递归方式编写它会更容易。
  • 请向我们展示您的尝试。
  • 我无法尝试,因为我不知道该写什么。
  • 我必须使用递归,因为它是指令。我知道有些东西效率更高,但这只是为了展示递归函数的工作原理。

标签: python recursion


【解决方案1】:

一种方法:

def recursive_sum(a, b):
    
    # if one of the list is empty return the empty list
    if not a or not b:
        return []
    # find the sum of each of the first elements
    val = a[0] + b[0]
    
    # return the concatenation of the first sum with the recursive sum for the rest of the lists 
    return [val, *recursive_sum(a[1:], b[1:])]

输出

[3, 6, 9]

作为@Stef 建议的替代方案,使用:

def recursive_sum(a, b):
    if not a or not b:
        return []
    return [a[0] + b[0]] + recursive_sum(a[1:], b[1:])

表达式:

*recursive_sum(a[1:], b[1:])

被称为拆包,基本上可以说 [1, 2, 3] 等同于 [1, *[2, 3]],请参阅此 link 了解更多信息。

【讨论】:

  • 可以请您帮个忙吗?您能否简要解释一下这一行发生了什么 return [a[0] + b[0], *recursive_sum(a[1:], b[1:])]
  • 尤其是乘号
  • @Jakeyyyy 在此上下文中的星号表示解包,而不是乘法。 x = [b, c, d]; y = [a, *x]x = [b, c, d]; y = [a, b, c, d]x = [b, c, d]; y = [a] + x 基本相同。所以return [a[0] + b[0], *recursive_sum(a[1:], b[1:])]return [a[0] + b[0]] + recursive_sum(a[1:], b[1:])是一样的
  • @Stef 对于最后一部分,您是否使用星号等于加号?因为这是您在原始示例中所做的唯一更改。我尝试了带有加号的那个,但出现错误。
  • 不,星号不是加号。请注意我是如何更改括号的。星号表示拆包。 [a, *[b, c, d]][a, b, c, d] 相同。结果与[a] + [b, c, d] 相同。但星号肯定不是加号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
相关资源
最近更新 更多