地图功能出现问题



我对python很陌生,我正在玩素数代码,我创建了一个函数,用于测试给定的任何正整数上的哥德巴赫猜想,如果猜想不适用,则返回False, 0,0,如果给定的数字遵循哥德巴赫猜想,则返回True, p1, p2,例如,哥德巴赫(10)将返回True, 3,7或哥德巴赫(21)将返回True, 2,19。

我还创建了一个函数,创建一个给定范围内的素数列表,是否有可能将我的哥德巴赫(n)函数映射到这个创建的列表,以便它返回一个包含类似[(bool, p1, p2),…]的新列表, (bool, p1, p2)]?如果是这样,我该如何编码呢?map()函数是我应该使用的吗?我相信我在这里错过了一些重要的东西,因为我总是得到一个错误说:'tuple'对象是不可调用的。

这是最有可能导致问题的原因:

def goldbachlist(x):
primes=listofprimes(x)
gold=list(map(goldbach(x), primes))
return gold

我试着根据您的说明创建程序。我不确定您是否已经实现了您没有以与我相同的方式列出的功能,但我已经在我的机器上进行了测试,并验证了我得到了您想要的结果。请注意,jwillis0720的文章使用了一种更优雅的列表过滤实践。

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)))

如果我理解正确的话,你需要映射你的素数到你的哥德巴赫函数

def goldbachlist(x):
primes=listofprimes(x)
gold=list(map(lambda x: goldbach(x), primes))# gold will have [(True,3,7)...
return gold

但是,如果您试图删除非素数,则可以过滤掉虚假形式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

最新更新