我必须优化代码,因为代码的运行时间超过了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 8
和AI.append(int(input())) = 2 2 1 1 1 5 5 5
.效果很好。
如果输入是k_m_n = 999 999 256000
和AI.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
发布于 2016-06-05 04:58:57
您的主要罪魁祸首是计数代码,如果n
是输入的数量,而m
是唯一输入的数量,则计数代码不必要地使用n
进行缩放。即,这一部分:
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)
https://stackoverflow.com/questions/37638535
复制相似问题