私はプロジェクトのユーラー問題5をやっています。私のループが見つけた最初の番号が必要です(最小であるためです)。最初の結果が見つかるとループします。ブレークを使用しようとしましたが、動作しません。ここに私のコードです:最初に見つかった答えを出力してループを終了する簡単な方法
"""2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"""
dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime;
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime
for x in range(20, 999999999, 20): # step has to be 20 so the number can be divisible by 20
if all(x % n == 0 for n in dividers):
print(x)
結果:
/usr/bin/python3.5 "/home/michal/Desktop/Project Euler/Problem5.py"
232792560
465585120
698377680
931170240
Process finished with exit code 0
は休憩と試みたが、それだけで(ちょうど私のプリントを移動しなければならなかった
dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime;
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime
for x in range(20, 999999999, 20): # step has to be 20 so the number can be divisible by 20
if all(x % n == 0 for n in dividers):
break
print(x)
'break'はあなたが望むものを正確に行うべきです。あなたはそれをどのように使ってみましたか? – Hamms
あなたのインデントを見ることができるように私のコードをコメントに書式設定する方法はありません...私のメインポストを編集するつもりです – doublemc
'break'の有無にかかわらずあなたの例のインデントの違いを注意深く見て、 Pythonで動作します。 – Hamms