python 求和的代码_用于条件求和的Python代码

The task is following: sum the list elements with even indexes and multiply the result by the last list's elemet.

I have this oneliner solution code in Python.

array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]

print sum(i for i in array if array.index(i) % 2 == 0)*array[-1] if array != [] else 0

My result is -1476 ( The calculation is: 41*(-37-19+29+3-64+36+26+55+84-65) )

The right result is 1968.

I can't figure it out why this code is not working correctly in this particular case.

解决方案

There is a repeated element 84 in the list, thus array.index does not work as you expected it to be. Also, your code has a quadratic complexity which is not required.

To fix your code with a minimum amount of edit, it would look something like this:

array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]

print sum(array[i] for i in range(len(array)) if i % 2 == 0)*array[-1] if array != [] else 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值