[英]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我已经尝试了以下代码,当我设置 lower = 0 和 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)
There are two things that you could do here.您可以在这里做两件事。
Memoization记忆
There's already a great explanation of what memoization is elsewhere on this site [link] , but here's how it's relevant to your problem:这个网站[link]上的其他地方已经有一个很好的解释,但这里是它与您的问题的相关性:
sumPdivisors
is called very frequently in the for-loop at the bottom of your code snippet. sumPdivisors
在代码片段底部的 for 循环中被非常频繁地调用。 For really large inputs n
, it will take a long time to run.对于非常大的输入
n
,运行需要很长时间。
sumPdivisors
is called with the same input n
multiple times.使用相同的输入
n
多次调用sumPdivisors
。
You can speed things up by saving the result of calling sumPdivisors
on different inputs somehow, like in a dictionary that maps integers to the resulting output when you call sumPdivisors
with that corresponding integer.您可以通过以某种方式保存在不同输入上调用
sumPdivisors
的结果来加快速度,例如当您使用相应的 integer 调用sumPdivisors
时,将整数映射到结果 output 的字典中。 This is kind of what memoization is.这就是记忆化的一种。 You're precomputing the possible outputs of
sumPdivisors
and storing them for later.您正在预先计算
sumPdivisors
的可能输出并将它们存储起来以备后用。 Read the link for a more in-depth explanation.阅读链接以获得更深入的解释。
Don't add the numbers in sumPdivisors to a list不要将 sumPdivisors 中的数字添加到列表中
You can just add these numbers as you iterate instead of appending them to a list, then summing them.您可以在迭代时添加这些数字,而不是将它们附加到列表中,然后将它们相加。 This change won't have as great of an impact as adding memoization to your code.
此更改不会像在您的代码中添加 memoization 那样产生很大的影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.