如何通过替换python中的循环来减少算法中的执行时间

编程入门 行业动态 更新时间:2024-10-07 10:17:36
本文介绍了如何通过替换python中的循环来减少算法中的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试解决算法问题,请考虑以下列表:

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

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

在此问题中,我必须找到直到索引i的元素的平均值:

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)]

效果很好,问题是我提交时遇到了时间限制。我认为问题是for循环,因为当 len(l)大于十分之一时会花费很多时间一千。以前,我使用 sum()进行平均,但是当我打开 sum()到 reduce(lambda a,b:a + b,x)// len(x)算法变得更快(它解决了更多的测试案例)。如果我不是使用for循环,而是使用另一个函数(例如lambda),那么问题就解决了。那么您认为有办法吗?谢谢您的时间。

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.

推荐答案

您可以尝试使用 numpy.cumsum 并获取平均值

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]

应该很快,O(n),因为 numpy.cumsum 已经非常优化。如果仍然希望更快,则可以对其进行多线程处理。

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

更多推荐

如何通过替换python中的循环来减少算法中的执行时间

本文发布于:2023-11-30 15:33:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650520.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:执行时间   算法   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!