【发布时间】:2015-09-04 18:00:42
【问题描述】:
我正在努力优化 Python 代码。目标是获取一个整数列表并计算并输出列表中有多少对。一对被认为是 2 个数字,差异为 K(在这种情况下为 2)
例如:
k = 2
list = [1, 5, 3, 4, 2]
这里的配对将是(1,3), (5,3), (2,4)
答案是:3
我想提高代码效率,当前版本需要 8 秒或更长时间。
cProfile 告诉我for number in sorted_array: 是唯一需要花费所有时间的行。但我似乎无法弄清楚如何优化for 循环。
有没有人有任何经验或建议?非常感谢。
代码:
#generate random numbers
import bisect
import random
n_integers = random.sample(xrange(1, 29999), 29998)
####cProfile
import cProfile
pr = cProfile.Profile()
pr.enable()
#the difference between numbers we are looking for
k = 2
sorted_array = []
pairs_counter = 0
#insert N integers in array in sorted fashion and typecast
for number in n_integers:
bisect.insort_left(sorted_array, number)
#iterate over the array and calculate (number + K)
for number in sorted_array:
the_pair = number + k
#check if the number+K is in the array
if the_pair in sorted_array:
pairs_counter += 1
print pairs_counter
#Close cProfile
pr.disable()
pr.print_stats(sort = 'time')
c个人资料:
30075 function calls in 7.995 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 7.834 7.834 7.834 7.834 <ipython-input-5-19d578e3c582>:19(<module>)
29998 0.143 0.000 0.143 0.000 {_bisect.insort_left}
1 0.016 0.016 0.159 0.159 <ipython-input-5-19d578e3c582>:15(<module>)
【问题讨论】:
-
当您输入包含重复项(例如
[1,3,3,3,6])时,预期的输出是什么? -
我收到
30004 function calls in 0.091 seconds是不是你的电脑速度很慢? -
我也有一个运行时,其确切代码为 0.147 秒。 (2012 年末 macbook pro 15")
-
@MorganThrapp:
bisect -
@MorganThrapp 我有一台去年一代的 Mac,配备 8Gb DDR3 内存和 2.6 i5 处理器。可能您的计算机太强大了?))))但这是很好的结果。我在 iPython 笔记本中运行代码,所以我在控制台中尝试了 - 结果对于 30000 次调用是相同的 >7 秒。
标签: python optimization cprofile