所以我用python找到了一个解决方案,但它运行得非常慢,我意识到我在一个列表中存储了大量和的倍数。我试图通过添加“not in”来防止这种情况发生,但由于某种原因,添加这一行完全改变了我的答案。你知道为什么会这样吗?你知道吗
for i in range(13, 28123):
s = sum_divisors(i)
if s > i:
abundant_numbers.append(i)
check_list = list()
for i in abundant_numbers:
for j in abundant_numbers:
s = i + j
if s <= 28123 and s not in check_list: # only check when sum < 28123 and prevent duplicates
check_list.append(s)
else:
break
check_list.sort()
sum_ans = 0
for i in range(28123):
if not binary_search(check_list, i):
sum_ans += i
print 'sum', sum_ans
当我把它当作
if s <= 28123
很好用。只有在“不在”条件下才会出现问题。你知道吗
事实上当你这么做的时候
一旦
s
大于28123或在check_list
中,它就会中断。而且,s
在check_list
中的事实很可能在它大于28123之前发生。你知道吗为了防止这种情况,您可能需要重新定位
s not in check_list
布尔值,如下所示您得到了一个完全不同的结果,因为添加
not in
意味着break
现在也以check_list
中的成员身份为条件:你可能应该做:
您可以完全避免进行成员资格检查,只需将
check_list
设为集:相关问题 更多 >
编程相关推荐