[Tutor] prime numbers

Alan Gauld alan.gauld at yahoo.co.uk
Sat Nov 13 19:16:44 EST 2021


On 13/11/2021 14:43, coskun arslan via Tutor wrote:
Please always post code in plain text, the HTML text gets messed
up, and formatting is very important in Python.

In this case I'll try to reformat it as you probably had it...


my_list=[i for i in range(2,21)]
for i in my_list:
       for k in range(2,i):
              if i%k==0:
                  my_list.remove(i)
print(my_list)

> It gives eror List.remove(i) i is not in list.What is wronge?         

Please always post the full error text not a summary,
there is a lot of useful information contained in the
error text.

But in this case you are iterating over my list while at the
same time removing elements of the list. That's a bit like
cutting down the branch of the tree that you are sitting on.

Python goes looking for the item at position 6, say,  but
in the meantime you have deleted items 3 and 4 so item 6
is no longer at position 6. Python gets confused!
To fix that you can iterate over a copy of the list
(mylist[:] is an easy way to create a copy) and remove
from the original list.

By the way, there are much more efficient algorithms for
finding prime numbers. For example:
Think about how high you need to go to find the factors.
Take 24 as an example:
(1,24),(2,12),(3,8),(4,6),(6,4), ...
but wait, 6,4 is the same pair as 4,6.
We are repeating ourselves. So we only need to test
up to the square root of the target, int(24**0.5) => 4.

That saves a bunch of tests.

But there are even more powerful algorithms you can use.
Try a google search...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list