Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What am I missing here?

Thanks in advance.

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading