警告,这有点递归;)
我回答了这个问题:Python:如何获取列表中最长元素之前的所有元素? https://stackoverflow.com/questions/8740018/pythonhow-can-i-get-all-the-elements-in-a-list-before-the-longest-element/8740093
在我提交了另一个应该更快的答案之后(作者认为,我也是如此)。我尝试对不同的解决方案进行计时,但应该较慢的解决方案实际上更快。这让我觉得我的代码有问题。或者是吗?
import string
import random
import time
def solution1(lst):
return lst[:lst.index(max(lst, key=len))]
def solution2(lst):
idx, maxLenStr = max(enumerate(lst), key=lambda x:len(x[1]))
return lst[:idx]
# Create a 100000 elements long list that contains
# random data and random element length
lst = []
for i in range(100000):
s = "".join([random.choice(string.letters+string.digits) for x in range(1, random.randint(1,50))])
lst.append(s)
# Time the first solution
start = time.time()
solution1(lst)
print 'Time for solution1', (time.time() - start)
# Time the second solution
start = time.time()
solution2(lst)
print 'Time for solution2', (time.time() - start)
Update
在有人提到我为什么把它作为一个新问题之前。问题更多是关于我学习如何测量执行时间......
第二种解决方案中 lambda 的成本更高。
我分析了代码和配置文件数据,看起来第一个解决方案更快
As the wiki http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Re-map_Functions_at_runtime会说函数调用成本高昂,在第二个解决方案中,lambda 和 len 函数调用使其运行速度变慢
请注意,我已将列表的长度缩减为 1000 个元素
>>> cProfile.run('solution1(lst)')
5 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <pyshell#305>:1(solution1)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {max}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {method 'index' of 'list' objects}
>>> cProfile.run('solution2(lst)')
2004 function calls in 0.012 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.012 0.012 <pyshell#306>:1(solution2)
1000 0.006 0.000 0.009 0.000 <pyshell#306>:2(<lambda>)
1 0.000 0.000 0.012 0.012 <string>:1(<module>)
1000 0.003 0.000 0.003 0.000 {len}
1 0.003 0.003 0.012 0.012 {max}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)