如何在仍然使用 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)
**我试图通过将所有东西放在一个函数中来优化代码以减少函数调用的数量,但它仍然没有给我真正想要的速度。**