正确使用'如果不在'蟒蛇

时间:2017-05-24 12:40:55

标签: python if-statement

我正在处理项目的欧拉问题,特别是问题23: enter image description here

所以我在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

它工作正常。问题只发生在&#39; not in&#39;条件。

2 个答案:

答案 0 :(得分:1)

其实当你做的时候

... 
        if s <= 28123 and s not in check_list:
                check_list.append(s)
        else:
            break
...    

一旦s大于28123或位于check_list,它就会中断。并且scheck_list之内的事实很可能在大于28123之前发生。

为防止这种情况发生,您可能需要重新定位s not in check_list布尔值,如此

... 
        if s <= 28123:
                if s not in check_list:
                    check_list.append(s)
        else:
            break
... 

答案 1 :(得分:1)

您获得了完全不同的结果,因为添加not in表示break现在也受check_list成员身份限制:

你可能应该这样做:

if s <= 28123:
    if s not in check_list:
        check_list.append(s)
else:
    break

您可以完全避免进行会员资格检查,只需将check_list设为设置

check_set = set()
for i in abundant_numbers:
    for j in abundant_numbers:
        s = i + j
        if s <= 28123:  
            check_set.add(s)
        else:
            break
相关问题