【问题标题】:How to optimize the python code (running time should be less than 10s)?如何优化python代码(运行时间应该小于10s)?
【发布时间】: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 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

【问题讨论】:

  • 你用的是python 2还是python 3?
  • 显然是 3,但这是什么计算?
  • 我正在使用 Python3
  • @MK:查看更新
  • 你试过profiling你的代码来定位瓶颈吗?

标签: python performance python-3.x optimization


【解决方案1】:

如果n 是输入数而m 是唯一输入数,则计数代码会不必要地与O(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)

【讨论】:

  • 我不明白我的代码的哪一部分需要替换为您的代码?
猜你喜欢
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
相关资源
最近更新 更多