如何优化python代码(运行时间应小于10s)?

时间:2016-06-05 04:43:39

标签: python performance python-3.x optimization

我必须优化代码,因为代码的运行时间超过10s。如果输入长度增加然后输出高于10s,则代码对于小输入完全正常(小于10s)。

import re, time
#from collections import OrderedDict
final_dict = {}
k_m_n = input()
k_m_n = list(map(lambda x: int(x), re.findall(r'([0-9]+)', k_m_n)))
AI = []
start = time.time()
for i in range(k_m_n[2]):
    AI.append(int(input()))
AI_sort, l = sorted(AI), len(AI)


i = 0
while i < l:
    final_dict[AI_sort[i]] = cnt = AI_sort.count(AI_sort[i])
    i += cnt
print(final_dict)
i = 0
for k in sorted(final_dict, key=final_dict.get, reverse=True):
    if i < k_m_n[0]:
        print(k)
        i += 1

print(time.time()-start)

如果输入是

k_m_n = 3 3 8AI.append(int(input())) = 2 2 1 1 1 5 5 5。它工作正常。

如果输入为k_m_n = 999 999 256000AI.append(int(input()))= 1..999..1...999(则时间超过10s)。请帮忙。

K = 3: Number of output I want to see
m = 3: Number of different types of numbers
n = 8: List of numbers

Suppose 
AI.append(int(input())) = 2 2 1 1 1 5 5 5
Here there are 3 types of number provided (2,1,5) # m
Total numbers in the list are = 8 # n
Outputs required in lexical order here is 1 5 2 #k.. although 1 and 5 are repeated 3 times but I need to print 1 then 5 then 2

1 个答案:

答案 0 :(得分:3)

您的主要罪魁祸首是计数代码,如果O(m*n)是输入数量且n是唯一输入数量,则不必要地使用m进行缩放。也就是说,这部分:

i = 0
while i < l:
    final_dict[AI_sort[i]] = cnt = AI_sort.count(AI_sort[i])
    i += cnt

此实现完全遍历列表以计算列表中每个唯一元素的元素,从而导致总计m*n次迭代(对于您的大型示例,导致约2.56亿次迭代)。

将它切换到这个实现解决了这个问题,并且相当多地改进了运行时间(尽管如此,我还没有开始10秒以上,但这可能是硬件性能的差异):

final_dict = {}
for a in AI_sort:
    final_dict[a] = final_dict.get(a, 0) + 1

尽管如此,该计划还有其他一些不必要的东西。它可以用这么少的代码编写:

import collections

k, m, n = [int(x) for x in input().split()]
occurrences = collections.Counter(int(input()) for i in range(n))
for num, seen in occurrences.most_common(k):
    print(seen)