In this exercise, we compute the distance between two points where the first is 2D and the second is 3D. How do we compute their difference when the dimensions are different?
Answer
If we have points p1 and p2 represented as arrays and the dimension, that is, the size of the array, of p1 is less than the dimension of p2. Then we make sense of the distance between these points by adding enough zeros to the end of the array for p1 until the sizes of the arrays are equal. Explicitly, if p1 = [1,0] and p2 = [1,1,1,1], then Distance(p1,p2) is the same as Distance([1,0,0,0], p2).
Blockquote
def euclidean_distance(pt1, pt2):
distance = 0
â# We will be adding code here nextâ
for i in range(len(pt1)):
distance += (pt1[i] - pt2[i]) ** 2
It is giving me error:
Blockquote
Traceback (most recent call last):
File âscript.pyâ, line 10, in
for i in range(len(pt1)):
NameError: name âpt1â is not defined
Which is probably right pt1 and pt2 havenât been defined yet.
I know this question is two months old and youâve probably resolved the issue yourself, but just in case someone else comes along and sees this question, what I think is going on here is that you have indeed defined pt1 as a parameter of the function, but you are then using pt1 as a variable outside the function in your line âfor i in range(len(pt1)):â because itâs not indented (plus the indent problems for the for loop and the âdistance = 0â)
I think if your code is otherwise fine if itâs just indented correctly.
Like @jimbeason pointed, the identation thing is very important, absolutely. Although, it seems that the step 2 will only works if you pass the the step 3 code in that ; it is, when you return the square root of distance.