lambda magic to find prime numbers
Find prime number up to 100 with just 3 lines of code. The 4th line is for printing ;)
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
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
Comments
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)
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
print "prime" if filter(lambda i:x%i==0,xrange(2,int(math.sqrt(x))))==[] else "none"
print(isprime(-7))
print(isprime(7))