Skip to content

Instantly share code, notes, and snippets.

@atroche
Created July 15, 2011 14:41
Show Gist options
  • Save atroche/1084814 to your computer and use it in GitHub Desktop.
Save atroche/1084814 to your computer and use it in GitHub Desktop.
@property
def centroid(self):
lat_sum = 0
lon_sum = 0
point_count = 0
for point in self.locations_points:
lat_sum += point[0]
lon_sum += point[1]
point_count += 1
return (float(lat_sum) / point_count, float(lon_sum) / point_count)
@atroche
Copy link
Author

atroche commented Jul 15, 2011

I could do it like:

x = [p[0] for p in points]
y = [p[1] for p in points]
centroid = (sum(x) / len(points), sum(y) / len(points))

But then I'd be looping through points twice...

@jorgebastida
Copy link

@property
def centroid(self):
    count = len(self.locations_points)
    total = reduce(lambda x,y: [x[0] + y[0], x[1] + y[1]], self.locations_points)
    return map(lambda x: x/count, total)

Not sure if it'll faster :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment