在 Python 中使用埃拉托色尼筛法时出现索引错误

Index error while using Sieve of Eratosthenes in Python

当尝试使用埃拉托色尼筛算法查找素数时,使用了以下代码。执行时给出索引错误。

我找不到索引超出范围的原因。 我正在使用 Python 2.7

"""
This program will find all the prime numbers up to the entered number using Sieve of Eratosthenes Algorithm
"""

while True:
    print "\n" * 3
    list1 = []
    final = []
    max = raw_input("Enter number upto which you want to find prime numbers or enter 0 to exit :")
    if max.isdigit():
        d = int(max)
        for i in range (2,d):
            list1.append(i)
        print list1

        k = 0
        x = 0

        while True:
            temp = list1[k]
            final.append(temp)
            length = len(list1)

            if (k+1) != length:
                for x in range(k+1,length):
                    temp1 = list1[x]
                    temp2 = final[k]
                    if temp1 % temp2 == 0:
                        del list1[x]  
                k += 1
            else:
                break

        print(final)

    else:
        print ("Invalid Input...!!")
        continue

您要从列表中删除元素,这会使列表变短(因此,最初可以检查的元素将超出范围。也就是说,一旦删除 4 个,就会发现错误当你寻找第 5 个元素时。验证这一点的一种方法是抛出一个

import pdb; pdb.set_trace()

在您的代码中,每次都打印出 list1。您可以使用 c 前进到下一个循环迭代。

一个解决方案是将 list1 复制到名为 primes 的列表开始,然后从 primes 而不是 list1.

中删除元素

原因是del list1[x]行。解释器第一次进入该行后,不可避免地会出现 IndexError,因为 length - 1(你 for-loop 中 x 的上限)现在大于最后一个索引list1

两种可能的解决方案:

  1. 捕获 IndexErrorbreak for 循环然后

  2. 像这样使用while-loop

    if (k+1) != length:
        x = k+1
        while x < len(list1):
            temp1 = list1[x]
            temp2 = final[k]
            if temp1 % temp2 == 0:
                del list1[x]
            x += 1
        k += 1
    else:
        break