When we have two points of different dimensions, how do we make sense of their distance?


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?


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).


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) .

What does the empty space do at index 2 of the p2 list p2 = [1,1,,1,1] ?

I feel like this would throw a syntax error.


Well spotted! You are right :slight_smile:

I edited the FAQ. Thank you very much.

1 Like

On point 2 with the code:

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:

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.

Anyone else having similar issues?

the for loop should be part of the function (body). There pt1 is defined, its one of the function parameters.

1 Like

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.

Happy coding.

1 Like

def euclidean_distance(pt1, pt2):
distance = sum([(pt1[i] - pt2[i]) ** 2 for i in range(len(pt1))]) ** 0.5
return distance

1 Like

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.