tag:blogger.com,1999:blog-19967453.post2381965215730038336..comments2023-09-28T04:33:10.550-07:00Comments on Musings of a Software Developer: Detect Prime numbers in one line – Python CodeKrishna Bhargava Vangapanduhttp://www.blogger.com/profile/16813193547125152985noreply@blogger.comBlogger4125tag:blogger.com,1999:blog-19967453.post-42434431693981333892009-06-19T13:37:24.307-07:002009-06-19T13:37:24.307-07:00thanks man..that works great and is very fast from...thanks man..that works great and is very fast from what I noticed in a short time. Great work and thanks again. I wish you made a post as non-anonymous.Krishna Bhargava Vangapanduhttps://www.blogger.com/profile/16813193547125152985noreply@blogger.comtag:blogger.com,1999:blog-19967453.post-74694478740483041832009-06-19T13:33:40.494-07:002009-06-19T13:33:40.494-07:00A faster and more memory efficient way is to use &...A faster and more memory efficient way is to use "all" and the generator form of the nested comprehension as follows:<br /><br />[x for x in xrange(2,10000) if all( (x%j!=0 for j in xrange(2,int(x**0.5)+1)))]<br /><br />That way the inner loop quits as soon as it finds a factor.<br /><br />A 2x faster way would be to skip even numbers:<br /><br />[2] + [x for x in xrange(3,10000,2) if all( (x%j!=0 for j in xrange(3,int(x**0.5)+1,2)) ) ]Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-19967453.post-46095758243720793392009-04-27T05:12:00.000-07:002009-04-27T05:12:00.000-07:00nope would not work that way. When we say
primes ...nope would not work that way. When we say<br /><br />primes = [item for item in numbers if len([i for i in range(2,primes)])==0]<br /><br />we are trying to use the same "primes".. I see what you are saying but the list comprehension completes execution and only then stores the result in primes. So we cannot trace back into primes and this kind of a greedy approach would not work. <br /><br />To be precise, you would get a NameError complaining about "primes" not being defined.Krishna Bhargava Vangapanduhttps://www.blogger.com/profile/16813193547125152985noreply@blogger.comtag:blogger.com,1999:blog-19967453.post-84353053518499444752009-04-25T12:08:00.000-07:002009-04-25T12:08:00.000-07:00I am not much into python but i was wondering if y...I am not much into python but i was wondering if you can use<br />len([i for i in range(2,<B>primes</B>) if item%i==0])==0]. <br /><br />using primes list instead of the value 8?Anonymousnoreply@blogger.com