While writing a python program for calculating the sum of primes between 2 to n (both inclusive), I am getting the error "The generator is not callable"
Can anyone help with the error or suggest what am I missing here?
n = int(input())
sum = 0
sum = sum(list(filter((lambda n: n%y != 0 for y in range(2, n)), range(2, n+1))))
print(sum)
1. first error: "TypeError: 'generator' object is not callable"
this error raise because you pass to filter build-in method a generator, you "cover" the lambda method with parentheses:
filter((lambda n: n%y != 0 for y in range(2,n)), range(2,n+1))
Solution: "uncover" the parentheses
filter(lambda n: n%y != 0 for y in range(2,n), range(2,n+1))
2. second error: "SyntaxError: Generator expression must to be parenthesized":
lambda n: n%y != 0 for y in range(2,n)
the error is clear: n%y != 0 for y in range(2,n) is a generator and needs to be be parenthesized,
here you want to test if the number is a prime so you want to check if all the values from your generator are True
Solution: use the build-in method all
lambda n: all(n%y != 0 for y in range(2,n))
3. last error: "TypeError: 'int' object is not callable"
sum=0
this is happening because you are using sum build-in method name for your variable sum, so the sum is not anymore the built-in method but an integer
Solution: another name for your variable:
n_prime_sum = 0
here is your code with the fixes:
n = int(input())
n_prime_sum = 0
n_prime_sum = sum(list(filter(lambda n: all(n%y != 0 for y in range(2,n)), range(2,n+1))))
n_prime_sum
# n = 10
output:
17
also, you can define a function that generates all the prime btw 2 and n (both inclusive) then apply the sum build-in method on this function:
# original code by David Eppstein, UC Irvine, 28 Feb 2002
# with comments by Eli Bendersky, https://stackoverflow.com/a/568618
def gen_primes(n):
"""Much more efficient prime generation, the Sieve of Eratosthenes"""
D = {}
q = 2 # The running integer that's checked for primeness
while q <= n:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
n = int(input())
n_prime_sum = sum(gen_primes(n))
print(n_prime_sum)
# n = 10
output:
17
most of the code for the function gen_prime comes from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With