Reputation: 2921
I'm trying to get the sum of all the prime numbers below 2,000,000 in Python, using a lambda function. (I've bruteforced it, but that takes much too long, and I want a better solution.) Here is what I have so far:
def isPrime(n):
for x in range(2, int(n**0.5)+1):
if n%x==0: return False
return True
print reduce(lambda x: isPrime(x), [range(200)])
Now, this just prints numbers incrementing from 1 to 200, so I don't think reduce is working =\
Anyone have any tips?
Upvotes: 1
Views: 2573
Reputation: 1243
There are lots of things wrong here. The first is that you can replace lambda x: isPrime(x)
with simply isPrime
. Functions are first class in Python, which means you can just pass them around in the same way as integers or strings. The second is that you are passing a list of lists; [range(200)]
is a list containing the return value of range(200)
range returns a list so you are only reducing a single value. This gets around the third problem, which is that your reduce function should accept 2 arguments, as reduce calls the function passed on pairs of items as a time. As it is, there is only one item so the function is called 0 times and the first item on list is returned.
What I suspect you want to do is to filter the list, you can use the filter
function to do this or you can use a list comprehension which would look like this:
[x for x in range(200) if isPrime(x)]
Upvotes: 2
Reputation: 208485
There are a few odd things going on with your code.
filter()
, not reduce()
.lambda x: isPrime(x)
is equivalent to isPrime
(after all, isPrime
is already a function that returns the result of isPrime
).[range(200)]
creates a nested list. The only element in the outer list is a list with the numbers from 0 to 200. I think you just want the single list.So, try the following:
print filter(isPrime, range(200))
Upvotes: 2