'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))
I wanted to find the number of x and y values that satisfy the equation: x^2 - y^2 = 2000^2, but this code is not working, because, I can see some results when I use nested for-loops:
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))
What is wrong with the filter(), map() and lambda functions?
Solution 1:[1]
I think the right way to implement what you're doing is
import 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))
but it's much too slow for your input number, as you need to construct and filter a 4 million-item list. Better is
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))
which lets you iterate only over one number. (There are further improvements available if needed.)
Solution 2:[2]
Your issue is that 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 function.
So, you are applying the function to (x[0], y[0]), then (x[1], y[1]), then (x[2], y[2]), etc.
You should take a look at itertools.product to get the functional equivalent of nested loops.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Charles |
| Solution 2 |
