I have the following program:
def main():
print "Running"
primes = sieve(100000)
print "Sieve is done"
def sieve(n):
print "starting sieve"
primes = []
times = 0
numbers = range(2, n):
print "sieve array filled"
while len(numbers) > 0:
current = numbers[0]
primes.append(current)
numbers.remove(current)
times = times + 1
if (times % 10 == 0):
print str(times) + "th prime is " + str(current)
# Remove every multiple
for i in numbers:
if (i % current == 0):
numbers.remove(i)
When finding all the primes up to a large number (lets say ten thousand) I wanted to be able to see how far along the program is by looking at the output. So I decided I would print out every tenth prime. However, when printing it out, it waits until the very end of the program to print it. I added in sys.stdout.flush() right after the print statement but it didn't make any difference. I then tried running the script with python -u <file name> and still, no difference at all.
This is what I get as output:
Running
starting sieve
sieve array filled
Then after about a minute the rest of the output is shown at once.
Why can't I turn the buffer off? I'm trying to modify the code as little as possible.
numbers = range(2,n)rather than doing that append thing.for i in range(2, n)loop but I removed it earlier, but I hadn't noticed until now that I could simplify it even further. Good eye!numberslist while iterating over it. This could cause unseen problems. Not sure if it's related to this problem. Also the print statement hardly does any buffering at all, which means it just isn't ever executed..removeing elements fromnumberswhile you iterate over it.