[英]converting coordinates given in list of tuples to complex number
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. complex(item[0], item[1])
的简短版本是complex(*item)
,它将序列喷入单独的参数中。 And I think this is a little better because it will explicitly fail on tuples longer than 2 items. 而且我认为这会更好一点,因为它会在长度超过2项的元组上显式失败。
But it might be even clearer to just write item[0] + item[1] * 1j
. 但是,只写
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. 除了看起来像写一个复数的方式之外,这还避免了将
float
complex(…)
隐式转换为float
,从而使complex(…)
可以在Decimal
对象或sympy
常值表达式之类的内容上进行静默工作-在第一种情况下,您会遇到错误,第二个则是一个sympy
复杂的常量值表达式。 (Of course if you want to coerce things to complex
values, that's a negative rather than a positive.) (当然,如果您想将事物强制为
complex
值,那是消极的而不是积极的。)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.