【发布时间】:2018-12-13 15:48:45
【问题描述】:
如何优化代码以在最短的时间内运行,同时仍然使用 CPython 实现?
def detdivisors(n):
"""This function tests if the sum of the divisors of a given
a number is a perfect square and returns the sum if it is, and
false if it is not"""
import math
divisors = []
sum = 0
for i in range(1,n+1):
if n%i == 0:
divisors.append(i)
for i in range(0, len(divisors)):
sum = sum + (divisors[i]**2)
if (math.sqrt(sum)%1 == 0):
return sum
else:
return False
def list_squared(m, n):
"""This function runs for the previous function and returns a
list that has all the numbers that satisfy the condition and
their associated sums. """
answers = []
for i in range(m, n+1):
ans = []
if detdivisors(i) != False:
ans.append(i)
ans.append(detdivisors(i))
answers.append(ans)
return answers
num = int(input("Enter the beginning: "))
end = int(input("Enter the end: "))
ans = list_squared(num,end)
print(ans)
**我试图通过将所有内容放在一个函数中来优化代码以减少函数调用的数量,但它仍然没有给我我真正想要的速度。 **
【问题讨论】:
-
将所有内容移到一个函数中并不会真正影响您的执行速度。如果你追求速度,CPython 通常是不行的,除非你有一些 C 扩展,你可以调用它来在解释器之外工作。此外,您能否发布您认为缓慢(或不是最佳)的任何时间安排?您尝试了哪些措施(除了移动代码)来减少执行时间?尽管如此,代码冗余对程序没有帮助。
-
“end”的预期最大值是多少?该值是否足够小,以便您可以使用存储的素数列表?如果您的“结束”保证小于
2**32(超过四十亿),那么您只需要小于2**16的6542素数。这大大加快了除数之和的计算。如果你想优化代码,你需要考虑你愿意做出什么样的权衡——在这种情况下,增加内存和预先计算的值。如果您想要我的代码使用主要列表,请告诉我。 -
预期最大值为 1000,起始值为 1。我真的很想拥有您的代码,它一定会有所帮助。谢谢老哥!
标签: python math optimization mathematical-optimization cpython