如何使用过滤器、映射、lambda 求解 x^2 - y^2 = 2000^2?

How to solve x^2 - y^2 = 2000^2 using filter, map, lambda?

import numpy as np

#defining range
start = -5000000
end = abs(start)

x = np.linspace(start, end, abs(start) + end + 1)
y = np.linspace(start, end, abs(start) + end + 1)

print(x, y)

xy_dif_list1 = list(filter(lambda r: r == 2000**2, list(map(lambda a, b: a**2 - b**2, x, y))))

print(len(xy_dif_list1)) 

我想找出满足等式的 x 和 y 值的个数: x^2 - y^2 = 2000^2, 但是这段代码不起作用,因为,当我使用嵌套的 for 循环时,我可以看到一些结果:

xy_list = []
for x in range(-5000000, 5000000):
    for y in range(-5000000, 5000000):
        if x**2 - y**2 == (2000**2):
            xy_list.append((x, y))
            print(xy_list)

print(len(xy_list))

filter()、map() 和 lambda 函数有什么问题?

你的问题是 map doesn't create nested loops out of its iterable arguments. Instead, it steps through both of them sequentially in parallel, as though using the zip 函数。

因此,您将函数应用于 (x[0], y[0]),然后 (x[1], y[1]),然后 (x[2], y[2])等

您应该查看 itertools.product 以获得嵌套循环的等效功能。

我认为实施您正在做的事情的正确方法是

导入 itertools

# find [x, y] with x^2 - y^2 = target
def solve(target):
    # assumes target >= 1, not hard to adjust to solve for all
    xmax = (target+1)//2
    x = range(xmax + 1) # 0 to xmax
    y = range(xmax) # 0 to xmax - 1
    xy = itertools.product(x, y)
    soln = filter(lambda v: v[0]*v[0] - v[1]*v[1] == target, xy)
    return list(soln)

print(solve(1000))
#print(solve(2000*2000))

但是对于您的输入数字来说它太慢了,因为您需要构建和过滤一个 4 million-item 列表。更好的是

import math

def issquare(n):
    if (n < 0):
        return False
    m = math.isqrt(n)
    return m*m == n

# x^2 - y^2 = target
def solve2(target):
    # assumes target >= 1, not hard to adjust to solve for all
    xmax = (target+1)//2
    x = range(xmax + 1) # 0 to xmax
    soln = filter(lambda x: issquare(x*x - target), x)
    return list(map(lambda x: (x, math.isqrt(x*x - target)), soln))

print(solve2(1000))
print(solve2(2000*2000))

这让您只能迭代一个数字。 (如果需要,可以进一步改进。)