sheldonzy
sheldonzy

Reputation: 5961

deleting sets from a set while iterating in python

I'm trying to implement something similar to Sieve of Eratosthenes. I want to remove all non prime numbers in a given range from the set, and sum up all the prime number to the given number.

number_set = set(list(range(1, given_number)))
sum_number = 0
for num in number_set:
    if isPrime(num):
        sum_number += num
        prime_set = set(list(range(0, big_number, num)))
        number_set -= prime_set

print(sum_number)

Obviously I got the error -

Set changed size during iteration

I'm new to python so the syntax is unfamiliar. As far as I understood from other threads, I can use dictionary and use the for loop on number_set.keys() (right?), but I wanted to ask, is it possible to correct this for loop?

Upvotes: 1

Views: 99

Answers (1)

WKnight02
WKnight02

Reputation: 330

You must stop itering over the modified iterator. My approach is to restart the iteration after the modification, try to modify the set such as every already processed value is not re-processed, and maybe call it a day.

The exception you are having is just a limitation about sets not liking being iterated over and modified at the same time.

number_set = set(list(range(1, given_number)))
sum_number = 0
done = False

while not done:
    for num in number_set:
        if isPrime(num):
            sum_number += num
            prime_set = set(list(range(0, big_number, num)))
            number_set -= prime_set
            break
    done = True

print(sum_number)

Disclaimer: Script might need adjustments on you part, I'm just illustrating the logic

Upvotes: 1

Related Questions