只用一行python代码实现累加和

问题描述 投票:0回答:4

我在面试时遇到了这个问题。 需求是用一行python实现累加和。我的答案是

def cum_sum(nums):
    return [sum(nums[0:i+1]) for i in range(len(nums))]

这非常难看,之前的结果后面没有被使用,导致冗余计算。我认为必须有一些高级的方法来实现它。

欢迎任何帮助。谢谢。

python
4个回答
5
投票

参见Python3.2+中的

accumulate
。这应该有效。

对于您的这段代码,相应的代码是:

from itertools import accumulate

return list(accumulate(nums)) 

编辑:更新后的代码是返回一个列表而不是迭代器。


2
投票

您可以尝试以下方法来获得一行中的累计和 -

nums = [10,20,30,40,50,60,70,80,90,100]

#Using base python 
[sum(nums[0:i[0]+1]) for i in enumerate(nums)]
#OUTPUT - [10, 30, 60, 100, 150, 210, 280, 360, 450, 550]

#Using Numpy
np.cumsum(nums)
#OUTPUT - array([ 10,  30,  60, 100, 150, 210, 280, 360, 450, 550])

0
投票

使用默认值和递归

代码

def cum_sum(lst, accum=0):
  return [lst[0] + accum] + accumulate(lst[1:], accum + lst[0]) if lst else []

测试

print(cum_sum([1, 2, 3, 4, 5])) # Output: [1, 3, 6, 10, 15]

0
投票
nums = [1,3,6,10]
n = len(nums)
nums.sort()
positive_contribution = 0
negative_contribution = 0
for i in range(n):
  negative_contribution += nums[i]
  positive_contribution += nums[i] * i # Positive contribution: current number is paired with all previous numbers i times.
  positive_contribution -= negative_contribution # Negative contribution: Subtract the sum of all previous numbers
return positive_contribution
© www.soinside.com 2019 - 2024. All rights reserved.