scarblac at pino.selwerd.nl
Tue Dec 12 07:00:30 EST 2000
DeHa <deha at poczta.onet.pl> wrote in comp.lang.python:
> I am new to Python, and just try to write my first program. But I have a
> small problem.
> My program should find first numbers in the set from 1 to 100000. I made
> such a code:
You probably meant prime numbers.
> first = range(100001)
> first = first[1:]
Instead, simply first = range(1,100001) would be easier. Actually,
the range should start at 2, since that is the first prime number
(and you don't want to delete numbers that are divided by 1).
> for i in first:
> if i != :
> #until end of the list
"for i in first" means that i will become all the elements of first in turn.
So i never becomes , since first only contains integers. And it already
loops until the end of the list.
> for j in first[first.index(i):]: #find all
> numbers divided by i
This also includes the number i itself, it shouldn't.
> if j % i == 0:
> first[first.index(j): first.index(j)] =  #and delete it
> from the list
You are deleting from a list while you are walking through it with 'for',
that's a bit tricky.
> And it doesn't work, and I don't konw why? Could anyone help me? I try
> to find answer in the tutorial, but the information in it doesn't change
It is easier to start with an empty list of primes, and add numbers that
can't be divided by the numbers in the list.
Something like this:
primes =  # We need one prime to start with
for candidate in range(3, 100001, 2):
for prime in primes:
if candidate % prime == 0:
# The 'else' clause happens when the 'break' never happened
This is not the fastest solution, but it works.
More information about the Python-list