【发布时间】:2016-10-04 22:42:16
【问题描述】:
我必须优化代码,因为代码的运行时间超过了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
【问题讨论】:
-
你用的是python 2还是python 3?
-
显然是 3,但这是什么计算?
-
我正在使用 Python3
-
@MK:查看更新
-
你试过profiling你的代码来定位瓶颈吗?
标签: python performance python-3.x optimization