Issue
I trying to create a code that calculate the distance between 2 point. I have 3 point (Point1, Point2, and Point3) and I want to compare each point combination (1 vs 2, 1 vs 3, and 2 vs 3) and find out which combination has the longest distance with expected result:
The distance between PointX and PointY is the longest, with distance {distance_XY}
The code that I used was:
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}')
But that code only worked with some number. When I try using the number below it worked:
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
When I try with different number like:
X = [0,0]
Y = [10,-10]
Z = [4,-3]
longest_distance(X,Y,Z)
The result should be The distance between PointX and PointY is the longest, with distance 14.142135623730951
, but nothing happened and there is no error so I don’t really know how to correct it
Solution
Nothing happens because None of the conditions you set are being met.
When using your input:
X = [0,0]
Y = [10,-10]
Z = [4,-3]
What happend is:
distance_XY = 14.14213…
distance_XZ = 5.0
distance_YZ = 9.219544…
We can clearly see that ‘distance_XY’ is the biggest, but all three conditions are False since:
14.14213… > 5.0 < 9.219544
Because of that you do not get any print. It is good practice to put else: and then write a general note stating that none of the conditions were met.
Nevertheless, I would try checking the maximum by doing the following:
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')
Answered By – Tomer Geva
Answer Checked By – Dawn Plyler (BugsFixing Volunteer)