I am trying to get the centroid for a series in n-dimensions.
This is what I have tried:
JavaScript
x
10
10
1
def get_centroid(point1, point2):
2
return sum((q + p) / 2 for p, q in zip(point1, point2))
3
4
p = [1, 2, 3, 4, 5, 6, 7]
5
6
q = [2, 3, 4, 5, 6, 7, 8]
7
8
get_centroid(p, q)
9
Out[18]: 31.5
10
But what I am trying to get is:
JavaScript
1
2
1
Out[]: [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]
2
What am I missing here?
Thanks in advance.
Advertisement
Answer
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 averages- Instead you need average of the corresponding values in each list/points
- 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
JavaScript
1
9
1
def get_centroid(point1, point2):
2
return [(q + p) / 2 for p, q in zip(point1, point2)]
3
4
p = [1, 2, 3, 4, 5, 6, 7]
5
6
q = [2, 3, 4, 5, 6, 7, 8]
7
8
print(get_centroid(p, q))
9
Output
JavaScript
1
2
1
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]
2