[英]prime number filter display no numbers
我正在嘗試在 python 中構建一個主過濾器,但列表中沒有 append 編號。 感謝您的反饋。 我認為問題在於
import sys
Primos =[2]
Teste = 1
Start = 0
End = 100
p = int in Primos
while Teste >= Start and Teste <= End:
if Teste % 2 == 0:
Teste = Teste + 1
elif Teste != 5 and (Teste % 5) != 0: //with this line, output is [2,5] without is [2,1]
Teste = Teste + 1
elif Teste in Primos and (Teste % p for p in Primos) != 0:
Teste = Teste + 1
else:
Primos.append(Teste)
Teste = Teste + 1
if Teste == End:
End = End + 100
Start = End - 100
if Teste == 1000 or End == 1000:
sys.exit()
print("\n",Primos)
這是嘗試編寫代碼的調試版本
Primos = [2]
Teste = 2 # Don't start this at 1, you don't want 1 in your primos
Start = 2
End = 100
while Teste >= Start and Teste <= End:
if Teste % 2 == 0:
Teste = Teste + 1
elif Teste != 5 and Teste % 5 == 0:
# If Teste is not equal to 5, but is divisible by 5, move to the next number
Teste = Teste + 1
elif any(Teste % p == 0 for p in Primos):
# If any prime in primos divides Teste, move to the next number
Teste = Teste + 1
else:
# Teste is prime, put it in the list
Primos.append(Teste)
Teste = Teste + 1 # Very important this is indented inside the else block
print(Primos)
您應該將其與您編寫的內容進行比較,注意錯誤並弄清楚如何通過一次一行地瀏覽代碼自己找到它們。
我還要指出,明確地檢查可被 2 和 5 整除不會使您的代碼比執行更快
Primos = [2]
for Teste in range(3, 100):
if not any(Teste % p == 0 for p in Primos):
Primos.append(Teste)
print(Primos)
這是因為any
function 將在找到第一個True
值后立即停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.