### lambda magic to find prime numbers

Find prime number up to 100 with just 3 lines of code. The 4th line is for printing ;)

``` nums = range(2, 100) for i in range(2, 10):     nums = filter(lambda x: x == i or x % i, nums) print nums```

Isn't it amazing?

Check my new post about Prime number: http://love-python.blogspot.com/2010/11/prime-number-generator-in-python-using.html

Zaman said…
It is really amazing!!!! the easyest way/code to find out primes that ever I have seen.
kiilerix said…
print [x for x in range(2,100) if not [t for t in range(2,x) if not x%t]]
kurazu said…
try this:
l = lambda n: reduce(lambda x,y: reduce(lambda a,b: a and (y % b != 0), x, True) and x+[y] or x, xrange(2, n + 1), [])

l(200)
Unknown said…
These methods use a lot of memory, be that due to lambda (recursion) or lists. Better to use Python generators instead.

Also, for the nested for loop, you only need to consider up to the square root of x. And for checking if there exist no x%y in a generator, use the python 'any' function - this is also a lot faster.

So, here we go:

from math import sqrt

for x in xrange(2,1000000):
if not any(y for y in xrange(2,1+int(sqrt(x))) if not x%y):
print x
Kreker said…
x=10000
print "prime" if filter(lambda i:x%i==0,xrange(2,int(math.sqrt(x))))==[] else "none"
extramiles said…
isprime = lambda x: int(x) > 0 and (x == 2 or x == 3 or [x % i == 0 for i in range(2,int(x**0.5)+1)].count(True) == 0)

print(isprime(-7))
print(isprime(7))