I'm pretty new to python, and am playing around with codes for prime numbers, I created a function that tests the goldbach conjecture on any positive integer given, and returns False, 0, 0 if the conjecture does not apply, and returns True, p1, p2 if the given number follows the goldbach conjecture, for example, goldbach(10), would return True, 3, 7 or goldbach(21) would return True, 2, 19.
I also created a function that creates a list of prime numbers in a given range, is it possible to map my goldbach(n) function to this created list, so that it returns a new list containing something like [(bool, p1, p2), ..., (bool, p1, p2)]? If so, how would I go about coding this? Is the map() function even what I should be using? I believe I'm missing something important here, because I always get an error saying: 'tuple' object is not callable.
This is what is most likely causing the problem:
def goldbachlist(x):
primes=listofprimes(x)
gold=list(map(goldbach(x), primes))
return gold
CodePudding user response:
If I understand right, you need to map your primes ot your goldbach function
def goldbachlist(x):
primes=listofprimes(x)
gold=list(map(lambda x: goldbach(x), primes))# gold will have [(True,3,7)...
return gold
However if you are trying remove non primes, you can filter out the false form gold
def goldbachlist(x):
primes=listofprimes(x)
gold=list(map(lambda x: goldbach(x), primes))
filtered_gold = list(filter(lambda x: x[0],gold))
return filtered_gold
CodePudding user response:
I took a crack at creating the program from your specifications. I am not sure that you've implemented the functions you haven't listed the same way that I have, but I have tested this on my machine and have verified that I get the results you desire. Note that the post by jwillis0720 uses a more elegant list filtration practice.
def listofprimes(x):
s = []
for i in range(2, x):
print(i)
stop = False
for z in range(1, i):
if i % z == 0 and z != 1 and z != i:
stop = True
if not stop:
s.append(i)
return s
def goldbach(x):
primes = listofprimes(x)
for i in primes:
for j in primes:
if i j == x:
return (True, i, j)
return (False, 0, 0)
def goldbachlist(x):
primes = listofprimes(x)
print(primes)
gold=list(map(lambda x: goldbach(x), primes))
finalG = []
for g in gold:
if(g[0] == True):
finalG.append(g)
return finalG;
print(goldbachlist(int(500)))