Python Eratosthenes Sieve Algorithm Optimization

后端 未结 6 748
再見小時候
再見小時候 2020-12-21 13:09

I\'m attempting to implement the Sieve of Eratosthenes. The output seems to be correct (minus \"2\" that needs to be added) but if the input to the function is larger than 1

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-21 13:45

    Warning: removing elements from an iterator while iterating on it can be dengerous...

    You could make the

        if(thing % divisor == 0) and thing != divisor:
    

    test lighter by splitting it in the loop that breaks when you arrive to the index of 'divisor' and then the test:

    for thing in numberList_fromDivisorOn:
        if(thing % divisor == 0):
            numberList.remove(thing)
    

提交回复
热议问题