I have written the following code for calculating the closest pair in a plane. The code works fine but I have two questions. First, is there a shorter/better way to convert the representation of points from tuples to complex in the first function? and second, is the way I have passed the first function to the second function correct?
import sys
x = [1, 4]
y = [1, 5]
def to_complex(hor, ver):
list_of_points = list(zip(hor, ver))
list_of_points.sort(key=lambda el: (el[0], el[1]))
complex_points = [complex(item[0], item[1]) for item in list_of_points]
return complex_points
# Brute force algorithm.
def brute_force(points=to_complex(x, y)):
n = len(points)
if n < 2:
return sys.maxsize
else:
min_distance = sys.maxsize
for i in range(n):
for j in range(i + 1, n):
if abs(points[i] - points[j]) < min_distance:
min_distance = abs(points[i] - points[j])
closest_pair = (points[i], points[j])
return min_distance, closest_pair
print(brute_force())
A shorter version of complex(item[0], item[1])
is complex(*item)
, which splats a sequence into separate arguments. And I think this is a little better because it will explicitly fail on tuples longer than 2 items.
But it might be even clearer to just write item[0] + item[1] * 1j
. Besides looking like the way you write a complex number, this also avoids the implicit conversion to float
that allows complex(…)
to silently work on things like Decimal
objects or sympy
constant-valued expressions—you'll get an error in the first case, and a sympy
complex constant-valued expression in the second. (Of course if you want to coerce things to complex
values, that's a negative rather than a positive.)
You can write your algorithm as follows
# Brute force algorithm.
def brute_force(hor, ver):
# Convert points to complex
points = [complex(x, y) for x, y in zip(hor, ver)]
n = len(points)
min_distance = sys.maxsize
closest_pair = None
if n < 2: return min_distance
else:
for i in range(n):
for j in range(i+1, n):
temp = abs(points[i] - points[j])
if temp < min_distance:
min_distance = temp
closest_pair = (points[i], points[j])
return min_distance, closest_pair
x = [1, 4, 3, 1]
y = [1, 5, 1, 5]
brute_force(x,y)
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