Python 3.x 我想提高我的多行输入算法的速度。python查找列表中消耗性元素的平均值
我需要从列表中找到连续元素的平均值。 首先,我被赋予了列表的长度 然后列出数字 然后给出我需要执行多少测试(有输入的几行) 然后给我几个输入来执行测试(需要打印尽可能多的带有结果的行) 测试的每一行由列表中的开始和结束元素组成Python 3.x 我想提高我的多行输入算法的速度。python查找列表中消耗性元素的平均值,python-3.x,algorithm,Python 3.x,Algorithm,我需要从列表中找到连续元素的平均值。 首先,我被赋予了列表的长度 然后列出数字 然后给出我需要执行多少测试(有输入的几行) 然后给我几个输入来执行测试(需要打印尽可能多的带有结果的行) 测试的每一行由列表中的开始和结束元素组成 My algorithm: nu = int(input()) # At first I am given lenght of list numbers = input().split() # then list with number
My algorithm:
nu = int(input()) # At first I am given lenght of list
numbers = input().split() # then list with numbers
num = input() # number of rows with inputs
k =[float(i) for i in numbers] # given that numbers in list are of float type
i= 0
while i < int(num):
a,b = input().split() # start and end element in list
i += 1
print(round(sum(k[int(a):(int(b)+1)])/(-int(a)+int(b)+1),6)) # round up to 6 decimals
您没有详细说明限制条件,但我猜要平均的范围可能相当大。计算总和(k[int(a):(int(b)+1)]可能需要一段时间
但是,如果预先计算输入列表的部分和,则可以在固定时间内回答每个查询(范围内的数字总和是相应部分和的差值)。仍然不够快。
Example:
Input:
8 - len(list)
79.02 36.68 79.83 76.00 95.48 48.84 49.95 91.91 - list
10 - number of test
0 0 - a1,b1
0 1
0 2
0 3
0 4
0 5
0 6
0 7
1 7
2 7
Output:
79.020000
57.850000
65.176667
67.882500
73.402000
69.308333
66.542857
69.713750
68.384286
73.668333
i= 0
while i < int(num):
a,b = input().split() # start and end element in list
i += 1
for _ in range(int(num)):
a, b = [int(j) for j in input().split()]