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.
Use list comprehension instead of sum
function because:
sum
returns the sum of all elements of an iterable, so it is now returning the sum of the averagesTry 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]