【发布时间】:2016-02-19 17:28:48
【问题描述】:
我是 Python 新手,目前正在努力解决问题以提高我的编码技能。目前我正在研究一个问题,我必须stable sort 输入并输出反向稳定的排序值。我已经编程并在网站的在线判断中执行了代码,对于一个测试用例(不知道测试用例),我得到了Memory Limit Exceeded 错误。所以经过一番研究,我了解到代码中发生了memory leak,并且代码效率不高。所以我安装了python的memory_profiler来监控进程的内存消耗以及对我的代码的内存消耗的逐行分析。
请在下面找到来自memory_profiler 的输入详细信息、代码、输出和内存分析分析。
输入:
8
1 2
16 3
11 2
20 3
3 5
26 4
7 1
22 4
代码:
from collections import OrderedDict
@profile
def test_1():
print "Enter the number: "
n = raw_input()
k = []
v = []
print "Enter ID and M: "
for i in range(0,int(n)):
a, b = raw_input().split(' ')
k.append(a)
v.append(b)
d = OrderedDict(zip(k,v))
sorted_items = sorted(d.items(), key=lambda (k,v):int(v), reverse=True)
for i, j in sorted_items:
print i, j
if __name__ == '__main__':
test_1()
输出:
Line # Mem usage Increment Line Contents
================================================
2 10.520 MiB 0.000 MiB @profile
3 def test_1():
4 10.531 MiB 0.012 MiB print "Enter the number: "
5 10.551 MiB 0.020 MiB n = raw_input()
6 10.551 MiB 0.000 MiB k = []
7 10.551 MiB 0.000 MiB v = []
8 10.551 MiB 0.000 MiB print "Enter ID and M: "
9 10.551 MiB 0.000 MiB for i in range(0,int(n)):
10 10.551 MiB 0.000 MiB a, b = raw_input().split(' ')
11 10.551 MiB 0.000 MiB k.append(a)
12 10.551 MiB 0.000 MiB v.append(b)
13
14 10.551 MiB 0.000 MiB d = OrderedDict(zip(k,v))
15 10.555 MiB 0.004 MiB sorted_items = sorted(d.items(), key=lambda (k,v):int(v), reverse=True)
16 10.555 MiB 0.000 MiB for i, j in sorted_items:
17 10.555 MiB 0.000 MiB print i, j
预期输出(我能够得到想要的输出):
3 5
26 4
22 4
16 3
20 3
1 2
11 2
7 1
此代码对于更高的输入或更高的数字是否无效?从分析中我可以看到只有更少的内存使用,但对于那个特定的测试用例,我可以看到内存使用超过 16MB。 有人可以告诉我我在哪里做错了。我的方法是错误的还是流程是错误的?您能否告诉我为什么我无法按预期获得输出。提前致谢。任何帮助将不胜感激。
【问题讨论】:
-
预期输出是什么?为什么你认为它应该使用更少的内存?
-
更新了问题以显示预期的输出
-
看起来您的代码是正确的,我的修订版也是如此。既然没有办法知道测试用例(设计这个在线课程的人真的应该重新考虑这一点),让我们看看是否会刮名单并将
range更改为xrange会有帮助。 -
当然,我会尝试使用
xrange执行代码,并在结果中查看它给出的执行时间和内存。 -
不幸的是,这次也超出了内存限制 -
Memory limit exceeded 0.374 16628 KB:(
标签: python memory memory-management memory-leaks