对于多个条件,在 python 中使用和逻辑运算符的正确方法是什么?

What is the correct way to use and logical operator in python for multiple conditions?

在改进我的代码之前,我正在尝试暴力破解 projecteuler 问题。我无法在我的循环中使用多个条件和逻辑运算符。这是代码,编辑器没有显示错误,但它根本没有增加条件值,所以很明显有些条件是错误的。有人可以告诉我使用多个逻辑运算符的正确方法吗?

i = 20

while (i % 2 != 0 and i % 3 != 0 and i % 4 != 0 and i % 5 != 0 and
     i % 6 != 0 and i % 7 != 0 and i % 8 != 0 and i % 9 != 0 and
     i % 10 != 0 and i % 11 != 0 and i % 12 != 0 and i % 13 != 0 and
     i % 14 != 0 and i % 15 != 0 and i % 16 != 0 and i % 17 != 0 and
     i % 18 != 0 and i % 19 != 0 and i % 20 != 0):
    i = i + 20
else:
    print(i)

您似乎在寻找最小的数字,它是 1 到 20(含 1 到 20)所有整数的倍数。你从 20 开始,你想继续增加 20,直到满足你的条件。

在较小的情况下更容易看到问题。假设我们只关心 2、3 和 4。

我们想找到一个数字 i

i % 2 == 0 and i % 3 == 0 and i % 4 == 0

但是这个的否定是

not (i % 2 == 0 and i % 3 == 0 and i % 4 == 0)

或者,分发 not

i % 2 != 0 or i % 3 != 0 or i % 4 != 0

也就是说,如果any个数不能均分,你想增加20,而不是如果all个数他们没有。

例如,

20 可以被 2 整除,所以 i % 2 != 0 是假的,所以你有 False and i % 3 != 0 and.. etc,它仍然是假的。您的代码的工作版本看起来像

i = 20
while any(i % num != 0 for num in range(2,21)):
    i += 20

我在这里使用生成器表达式来避免所有重复。请注意,这比使用他们希望您使用的数学技巧要慢得多,因为最终答案有 9 位数字..