我試圖創建一個計算 2 點之間距離的代碼。我有 3 個點(Point1、Point2 和 Point3),我想比較每個點組合(1 vs 2、1 vs 3 和 2 vs 3)并找出哪個組合與預期結果的距離最長:
The distance between PointX and PointY is the longest, with distance {distance_XY}
我使用的代碼是:
def longest_distance(X,Y,Z):
a = X[0]
b = X[1]
c = Y[0]
d = Y[1]
e = Z[0]
f = Z[1]
distance_XY = (((a-c)**2) ((b-d)**2)) ** (1/2)
distance_XZ = (((a-e)**2) ((b-f)**2)) ** (1/2)
distance_YZ = (((c-e)**2) ((d-f)**2)) ** (1/2)
if distance_XY > distance_XZ > distance_YZ:
print(f'The distance between PointX and PointY is the longest, with distance {distance_XY}')
elif distance_XY < distance_XZ > distance_YZ:
print(f'The distance between PointX and PointZ is the longest, with distance {distance_XZ}')
elif distance_XY < distance_XZ < distance_YZ:
print(f'The distance between PointY and PointZ is the longest, with distance {distance_YZ}')
但是該代碼僅適用于某些數字。當我嘗試使用下面的數字時,它起作用了:
X = [0,0]
Y = [5,5]
Z = [10,10]
longest_distance(X,Y,Z)
The distance between PointX and PointZ is the longest, with distance 14.142135623730951
當我嘗試使用不同的數字時:
X = [0,0]
Y = [10,-10]
Z = [4,-3]
longest_distance(X,Y,Z)
結果應該是The distance between PointX and PointY is the longest, with distance 14.142135623730951,但什么也沒發生,也沒有錯誤,所以我真的不知道如何糾正它
uj5u.com熱心網友回復:
什么都沒有發生,因為您設定的條件都沒有得到滿足。使用您的輸入時:
X = [0,0]
Y = [10,-10]
Z = [4,-3]
發生的事情是:
距離_XY = 14.14213...
距離_XZ = 5.0
距離_YZ = 9.219544...
我們可以清楚地看到 'distance_XY' 是最大的,但所有三個條件都是 False,因為:14.14213... > 5.0 < 9.219544
因此,您不會得到任何列印。寫 else: 是一個很好的做法:然后寫一個一般說明,說明沒有滿足任何條件。
不過,我會嘗試通過執行以下操作來檢查最大值:
max_val = max(distance_XY, distance_XZ, distance_YZ)
if distance_XY == max_val:
print(f'The distance between PointX and PointY is the longest, with distance {distance_XY}')
elif distance_XZ == max_val:
print(f'The distance between PointX and PointZ is the longest, with distance {distance_XZ}')
elif distance_YZ == max_val:
print(f'The distance between PointY and PointZ is the longest, with distance {distance_YZ}')
else:
print('None of the conditions were met, something went wrong')
uj5u.com熱心網友回復:
您正在尋找三個值的最大值,但您要檢查的是順序。在您的第二個示例中:
distance_XY, distance_XZ, distance_YZ = 14.142135623730951 5.0 9.219544457292887.
這意味著您的第一個條件應該為真。但它不是,因為distance_XY > distance_XZ -> True(沒關系),但是distance_XZ > distance_YZ -> False. 所以第二個>導致整個條件變為假,即使這不相關,因為distance_XY是最大值。
嘗試以不同的方式定義您的條件以獲得最大距離。或者使用另一種最大方法。
一般來說,要除錯這樣的問題,請嘗試添加一些列印陳述句來查看中間值。然后試著想想給定這些值會出現什么問題。
對于使用最大值的簡潔方法,您可以執行以下操作:
def longest_distance(X, Y, Z):
(a, b), (c, d), (e, f) = X, Y, Z
distances = {("X", "Y"): (((a-c)**2) ((b-d)**2)) ** (1/2),
("X", "Z"): (((a-e)**2) ((b-f)**2)) ** (1/2),
("Y", "Z"): (((c-e)**2) ((d-f)**2)) ** (1/2)}
(max_name_x, max_name_y), max_value = max(distances.items(),
key=lambda x: x[1])
print(f'The distance between Point{max_name_x} and Point{max_name_y} '
f'is the longest, with distance {max_value}')
uj5u.com熱心網友回復:
嘗試獲取兩點之間的差異并將值存盤在變數中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440286.html
上一篇:條件定義變數(靜態if)
下一篇:在lua中定義邏輯運算子意味著
