【问题标题】:Python recursive through list [duplicate]Python通过列表递归[重复]
【发布时间】:2020-03-13 19:56:50
【问题描述】:

我需要帮助来创建一个将列表中的所有项目相乘的递归函数。代码如下:

def multiply(lst):
    if len(lst) < 1:
        return 1
    else:
        for x in range(len(lst)):
            return lst[x] * multiply(lst[x+1])

【问题讨论】:

  • 从移除循环开始。
  • return lst[0] if len(lst) == 1 else lst[0] * multiply(lst[1:])
  • 除非这是为了家庭作业,否则对这样的事情使用递归是个坏主意。
  • 非常感谢CRJ

标签: python


【解决方案1】:

你不需要递归循环。要么使用递归(不推荐,但作为演示):

# multiply([2,3,4]) == 2 * multiply([3,4])
#                   == 2 * (3 * multiply([4]))
#                   == 2 * (3 * (4 * multiply([])))
#                   == 2 * (3 * (4 * 1))
#                   == 2 * (3 * 4)
#                   == 2 * 12
#                   == 24
def multiply(lst):
    if not lst:
        return 1
    else:
        return lst[0] * multiply(lst[1:])

或循环:

# multiply([2, 3, 4])
#  product = 1
#  product *= 2  (== 2)
#  product *= 3  (== 6)
#  product *= 4  (== 24)
def multiply(lst):
    product = 1
    for x in lst:
        product *= x
    return product

【讨论】:

  • multiply = math.prod :-)
  • 我假设这不会被接受为作业的答案:)
猜你喜欢
  • 2017-02-21
  • 2011-07-21
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2020-02-14
  • 1970-01-01
  • 2012-09-10
相关资源
最近更新 更多