for循环里python计算程序跑的时间_如何通过替换python中的循环来减少算法中的执行时间...

I'm trying to solve an algorithm problem,consider the following list:

l = [100, 20, 50, 70, 45]

in this problem I have to find the average of the elements up to index i:

i = 0

100

i = 1

(100 + 20) //2 = 60

i = 2

(100+20+50) // 3 = 56

...

the final result should be stored in a list:

[100, 60, 56, 60, 57]

this is my code so far:

from functools import reduce

def meanScores(l):

def av(x):

return reduce(lambda a, b: a+b,x)//len(x)

return [av(l[:i]) for i in range(1,len(l)+1)]

It works fine the problem is that when I submitted it, I faced a time limit execution.I think the problem is the for loop since it takes a lot of time when len(l) is more than ten-thousand. Previously I used sum() to do the averaging but that took a lot of time too, when I turned that sum() to reduce(lambda a, b: a+b,x)//len(x) the algorithm got faster(It solved more test cases).I think that if instead of an for loop I use another function(like lambda) then the problem is solved.So do you think there is a way? thank you for your time.

解决方案

You can try to use numpy.cumsum and get the average dividing by the index+1 of the cumsum list.

import numpy as np

l = [100, 20, 50, 70, 45]

l_cumsum = np.cumsum(l)

l_indices = np.arange(1,len(l)+1,1)

l_average = np.divide(l_cumsum, l_indices).tolist()

print(l_average) # Outputs [100.0, 60.0, 56.666666666666664, 60.0, 57.0]

It should be pretty fast, O(n), since numpy.cumsum is very optimized already. If you still want it faster you could multithread it.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值