Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 我一直在计算子集的平均值_Python 3.x_Performance_Loops_Io - Fatal编程技术网

Python 3.x 我一直在计算子集的平均值

Python 3.x 我一直在计算子集的平均值,python-3.x,performance,loops,io,Python 3.x,Performance,Loops,Io,我有一个工作代码块,但是HackerEarth上的在线法官不断返回一个计时错误。我对编码还不熟悉,所以我不知道如何加速我的代码。任何帮助都将不胜感激 N, Q = map(int, input().split()) #N is the length of the array, Q is the number of queries in_list =input().split() #input is a list of integers separated by a space array = l

我有一个工作代码块,但是HackerEarth上的在线法官不断返回一个计时错误。我对编码还不熟悉,所以我不知道如何加速我的代码。任何帮助都将不胜感激

N, Q = map(int, input().split())
#N is the length of the array, Q is the number of queries
in_list =input().split()
#input is a list of integers separated by a space
array = list(map(int, in_list))
from numpy import mean
means=[]
for i in range(Q):
   L, R = map(int, input().split())
   m= int(mean(array[L-1:R]))
   means.append(m)

for i in means:
    print(i)

任何建议都将是惊人的

您可能需要避免在循环中执行
O(N)
操作。目前,切片和
mean
调用(需要汇总切片中的项目)都非常慢。所以你需要一个更好的算法

我建议您对数字列表进行一些预处理,这样您就可以计算出切片中的值之和(而不需要实际执行切片并将它们相加)。通过使用
O(N)
空间,您可以在
O(1)
时间中计算每个和(使整个过程花费
O(N+Q)
时间,而不是
O(N*Q)

下面是我总结的一个快速解决方案,使用
itertools.accumulate
查找列表项的累积和。实际上,我并不保存项目本身,因为累积的总数就足够了

from itertools import accumulate

N, Q = map(int, input().split())
sums = list(accumulate(map(int, input().split())))

for _ in range(Q):
    L, R = map(int, input().split())
    print((sums[R] - (sums[L-1] if L > 0 else 0)) / (R-L+1))

感谢您的快速回复!我正在寻找提示,但我甚至不知道如何开始这样做。切片似乎是快速程序的死亡,因此找出如何在没有切片的情况下完成它将非常有帮助。我已经用一个实际的解决方案更新了我的答案,如果你自己还在解决这个问题,你可能想跳过。非常感谢!这真的很有帮助。