我已经写了一个程序,它应该打印出从0到100的所有合成数,但我一直收到错误"list index out of range“。
我能做些什么来修复它呢?
def isPrime(x):
if x==0:
return False
if x==1 or x==2:
return True
for i in range(2, x):
if x%i==0:
return False
break
elif x%i==1:
return True
else:
print("error")
i=0
num = list(range(100))
while i<100:
if isPrime(num[i]==True): #I get the error here
del (num[i])
i += 1
else:
i += 1
print(num)发布于 2020-05-07 23:42:04
因为当你在列表上循环时,你正在编辑它。在索引74处,该索引不再存在,因为列表的长度是73。请注意,您的主函数似乎没有按照您的预期工作。
from math import sqrt
from itertools import count, islice
def isPrime(n): # Taken from https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python/27946768#27946768
if n < 2:
return False
for number in islice(count(2), int(sqrt(n) - 1)):
if n % number == 0:
return False
return True
num = list(range(100))
to_delete = []
for i in num:
if isPrime(i): #I get the error here
to_delete.append(i)
final = [n for n in num if n not in to_delete]
print(final)正确的输出:
[0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99]发布于 2020-05-07 23:41:03
因为如果您的条件为真,您将删除一个元素,但仍在增加i。将您的代码更改为以下代码:
def isPrime(x):
if x==0:
return False
if x==1 or x==2:
return True
for i in range(2, x):
if x%i==0:
return False
return True
i=0
lim = 100
num = list(range(lim))
while i<lim:
if isPrime(num[i])==True: #I get the error here
del (num[i])
lim -=1
else:
i += 1
print(num)顺便说一句,你的代码包含了一个错误的if isPrime(num[i]==True),我已经修改过了。
输出:
[0, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99]因为你的isPrime算法也不正确,所以我已经纠正了它。
https://stackoverflow.com/questions/61661799
复制相似问题