python - How can I optimize my code to print amicable numbers?
问题描述
I have tried this following code and it takes a lot of time when I set lower = 0 and upper = 10000
def sumPdivisors(n):
'''This function returns the sum of proper divisors of a number'''
lst = []
for i in range(1,n//2+1):
if n%i == 0:
lst.append(i)
return(sum(lst))
lower = int(input("Enter the lower value of range: "))
upper = int(input("Enter the upper value of range: "))
lst = []
for i in range(lower, upper+1):
if i == 0:
continue
else:
for j in range(i, upper):
if i!=j and sumPdivisors(i) == j and sumPdivisors(j) == i:
lst.append((i,j))
break
print(lst)
解决方案
您可以在这里做两件事。
记忆
这个网站[link]上的其他地方已经有一个很好的解释,但这里是它与您的问题的相关性:
sumPdivisors
在代码片段底部的 for 循环中非常频繁地调用。对于非常大的输入n
,运行需要很长时间。sumPdivisors
n
多次调用相同的输入。您可以通过以某种方式保存调用
sumPdivisors
不同输入的结果来加快速度,例如在sumPdivisors
使用相应整数调用时将整数映射到结果输出的字典中。这就是记忆化的一种。您正在预先计算可能的输出sumPdivisors
并将它们存储起来以备后用。阅读链接以获得更深入的解释。
不要将 sumPdivisors 中的数字添加到列表中
您可以在迭代时添加这些数字,而不是将它们附加到列表中,然后将它们相加。此更改不会像在您的代码中添加 memoization 那样产生很大的影响。
推荐阅读
- c++ - 为什么 IntelliSense 自动完成功能不起作用?
- c# - 没有使用 DBContext 从 SQL 数据库返回数据
- git - How is Git accessing my GitHub credentials?
- python - 时间序列:从另一个数据框中填充 NaN
- r - Purrr ~ 操作符记录在哪里?
- c++ - 如何在 C++ 中将 Unix 纪元时间转换为 Pascal TDateTime(double)
- arrays - 连接不同大小的数组
- angular - Checkmarx 和 angular2 模板 xss 警告
- python - 模拟真实点击python
- idris - Idris2:相关总和类型区分