我是编程和python新手,希望能在寻找整数的素性方面得到一些帮助我读过一些实现Eratosthene筛的方法,但大多数方法似乎有点过于复杂(太多代码)。以下是我的方法,我需要帮助的部分位于“帮助”注释下面:

def prime_number(an_integer):
    if (an_integer <= 1):
        return False
    else:
        integer_list = list(range(2, an_integer +1))

        #HELP
        first_element = integer_list[0]
        for each_integer in integer_list:
            if (each_integer % first_element == 0) and (each_integer != first_element):
                integer_list.remove(each_integer)

        second_element = integer_list[1]
        for each_integer in integer_list:
            if (each_integer % second_element == 0) and (each_integer != second_element):
                integer_list.remove(each_integer)

        third_element = integer_list[2]
        for each_integer in integer_list:
            if (each_integer % third_element == 0) and (each_integer != third_element):
                integer_list.remove(each_integer)

        fourth_element = integer_list[0]
        for each_integer in integer_list:
            if (each_integer % fourth_element == 0) and (each_integer != fourth_element):
                integer_list.remove(each_integer)


        print (integer_list)

我该如何消除重复?

最佳答案

回答你的直接问题:

for element in integer_list:
    for each_integer in integer_list:
        if (each_integer % element == 0) and (each_integer != element):
            integer_list.remove(each_integer)

(我假设你的意思是fourth_element就是integer_list[3]
不过,请注意,现在有两个循环在integer_list上,在循环中您可以从列表中删除元素,这可能会给您带来麻烦。

关于python - 实现Eratosthenes筛分算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37755147/

10-11 19:10