我正在https://www.hackerrank.com/challenges/angry-children处理一个问题。我写了一个正确解决一些测试用例的解决方案。其他测试用例,提供更多输入,超时的情况。如何更改此代码以更快地处理?
N = int(input())
K = int(input())
D = K - 1
N_set = []
for n in range(N):
N_set.append(int(input()))
N_set.sort(reverse=True)
#Find differences between each integer in the list
D_set = []
for d in range(0,N-1):
D_set.append(N_set[d]-N_set[d+1])
D_Start = 0
D_End = D
min_summed_diff = 99999999999999
D_Start_Hold = None
D_End_Hold = None
count_down = len(D_set) - D + 1
while count_down:
#print(count_down)
temp_summed_diff = 0
for i in range(D_Start, D_End):
temp_summed_diff += D_set[i]
if temp_summed_diff < min_summed_diff:
min_summed_diff = temp_summed_diff
D_Start_Hold = D_Start
D_End_Hold = D_End
D_Start += 1
D_End += 1
count_down -= 1
K_set = N_set[D_Start_Hold:D_End_Hold+1]
unfairness = max(K_set) - min(K_set)
print(unfairness)
答案 0 :(得分:0)
两个初始循环将更快,方法循环被拉出循环。列表理解也更快。我跑了这个实验
from timeit import timeit
a = '''\
tem = []
for i in range(%d):
tem.append(int('1000'))
'''
b = '''\
tem = []
temapp = tem.append
for i in range(%d):
temapp(int('1000'))
'''
c = "tem = [int('1000') for i in range(%d)]"
for n in (10,1000, 1000000):
number = 1000000 // n
print(timeit(a%n, number = number))
print(timeit(b%n, number = number))
print(timeit(c%n, number = number))
print()
有了这些结果。
0.48560521545219426
0.3943799918166562
0.4146867965037263
0.372683063890642
0.3126639858171769
0.2900946187597775
0.36497313668305287
0.33567233916055894
0.3071572902003692
我相信这笔钱
temp_summed_diff = 0
for i in range(D_Start, D_End):
temp_summed_diff += D_set[i]
就是这个,会更快
temp_summed_diff = sum(D_set[D_start:D_end]
我没有看到任何其他加速。
答案 1 :(得分:0)
您可以大大提高计算最小不公平性的算法。
如果你的列表被排序,那么每个子列表的不公平性只是它的结束之间的差异,所以这一切都归结为找到所有长度为k的子列表的最小差异。
此外,在这种情况下,通常可以更快地避免input()
并直接从sys.stdin
阅读。
这整个问题只需6行python即可解决:
import sys
nrs = map(int, sys.stdin)
n, k = next(nrs), next(nrs)
nrs = sorted(nrs)
min_unfair = min(nrs[k+i-1] - nrs[i] for i in range(0, len(nrs)-k+1))
print(min_unfair)