Skip to content
Advertisement

Get Centroid from Sequence in N-Dimensions

I am trying to get the centroid for a series in n-dimensions.

This is what I have tried:

def get_centroid(point1, point2):
    return sum((q + p) / 2 for p, q in zip(point1, point2))

p = [1, 2, 3, 4, 5, 6, 7]

q = [2, 3, 4, 5, 6, 7, 8]

get_centroid(p, q)
Out[18]: 31.5

But what I am trying to get is:

Out[]: [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]

What am I missing here?

Thanks in advance.

Advertisement

Answer

Use list comprehension instead of sum function because:

  1. sum returns the sum of all elements of an iterable, so it is now returning the sum of the averages
  2. Instead you need average of the corresponding values in each list/points
  3. List comprehension creates a list of values, each value given by the formula you have already written for find the average

Try the following:

Code

def get_centroid(point1, point2):
    return [(q + p) / 2 for p, q in zip(point1, point2)]

p = [1, 2, 3, 4, 5, 6, 7]

q = [2, 3, 4, 5, 6, 7, 8]

print(get_centroid(p, q))

Output

[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement