在python 3.x中某些情况下出现超时错误

时间:2019-12-16 20:16:59

标签: python arrays python-3.x optimization median

我正在处理欺诈活动通知问题:https://www.hackerrank.com/challenges/fraudulent-activity-notifications/。我将以下代码编写为 解决这个问题。对于某些测试用例,此代码运行良好,但对于某些测试用例却失败,从而导致超时错误。谁能帮助我了解如何进行优化 并使其变得更好?

def calculate_median(lists):    
    n = len(lists)
    lists.sort()
    if n % 2 == 0: 
        median1 = lists[n//2] 
        median2 = lists[n//2 - 1] 
        median = (median1 + median2)/2
    else: 
        median = lists[n//2] 
    return median


my_list = [2,3,4,2,3,6,8,4,5]
d=5
n = len(my_list)
count = 0
start= 0
end = d
for i in range(0, len(my_list)):
    if end < n:
        seg_list = my_list[start:end]
        check_val = my_list[end]
        median_val = calculate_median(seg_list)
        if check_val >= 2 *median_val:
            count = count +1 
        start = start + 1
        end = end + 1

print(count)

1 个答案:

答案 0 :(得分:1)

我已经使用bisect_left和insort_left解决了这个问题。这是最优化的方法之一。

from bisect import bisect_left, insort_left
count = 0
listD = sorted(my_list[:d])

def median():
   return listD[d//2] if d%2 == 1 else ((listD[d//2] + listD[d//2-1])/2)

for i in range(d,n):
   if my_list[i] >= 2*median(): 
      count += 1
   del listD[bisect_left(listD, my_list[i-d])]
   insort_left(listD, my_list[i])
print(count)