我在python課上做一個問題。在測驗結果中,我的結果與答案有差異,
在最后的測驗中,
The nearest point to Point(-30, 9) is Point(-19, 19), but my code prints Point(-20,20)
不知道哪里不對?請幫我。謝謝
這是我的代碼
這是我的代碼。
import math
class Point:
"""Defines the Point class for a 2D point.
Data attributes:
x - the x-coordinate of type float
y - the y-coordinate of type float
"""
def __init__(self, x, y):
"""Creates a new Point object"""
self.x = x
self.y = y
def __repr__(self):
"""A string representation of this Point"""
return f"Point({self.x}, {self.y})"
def euclidean_distance(point1, point2):
"""returns the euclidean distance between two points"""
return math.sqrt((point1.x-point2.x) ** 2 (point1.y-point2.y) **2)
def closest_point(centre, points):
"""returns the nearest point in the list to the centre."""
new_dict = {}
for point in points:
distance = math.sqrt((centre.x-point.x) ** 2 (centre.y-point.y) **2)
new_dict[distance] = point
for keys,values in new_dict.items():
min_key = min(new_dict.keys())
return new_dict[min_key]
和下面的測驗結果:

請幫我解決這個問題,我的代碼哪里出了問題,以及如何修改它以獲得預期的結果。謝謝
uj5u.com熱心網友回復:
問題出在常規最接近點
- 使用您正在設定具有該距離的最后一個點對的字典(問題是多對具有相同的距離)
- 在下面的代碼中,使用了具有距離的第一對(答案與鏈接的解決方案一致)
- 不正確地回圈 new_dict 以找到最近點(不需要 dict)
代碼
def closest_point(centre, points):
"""returns the nearest point in the list to the centre."""
min_dist = float('inf') # initialize to infinity
min_point = None
for point in points:
distance = euclidean_distance(centre, point) # use function rather than recoding
if distance < min_dist:
min_dist = distance # using the first point with this min distance
min_point = point
return min_point
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523587.html
上一篇:如何將文本檔案行放入串列
下一篇:元素沒有附加到塊內的陣列中
