![](/img/trans.png)
[英]What is the correct way of grabbing an inner string in regular expressions for Python for multiple conditions
[英]What is the correct way to use and logical operator in python for multiple conditions?
在改善代碼之前,我正試圖強行解決一個項目專家問題。 我無法在循環中使用多個條件和邏輯運算符。 這是代碼,編輯器未顯示任何錯誤,但它只是不增加條件值,因此顯然某些條件是錯誤的。 有人可以告訴我使用多個邏輯運算符的正確方法嗎?
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之間的所有整數的整數倍。 您從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
換句話說,如果任何一個數字未能平均分配,您希望增加20,而不是所有數字均不能分配。
例如,20可以被2整除,因此i % 2 != 0
為False,所以您有False and i % 3 != 0 and.. etc
。 您的代碼的有效版本如下所示
i = 20
while any(i % num != 0 for num in range(2,21)):
i += 20
在這里我使用了生成器表達式來避免所有重復。 請注意,這比使用他們希望您使用的數學技巧要慢得多,因為最終答案有9位數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.