Reputation: 1
I am trying to implement the standard k-means algorithm in python but am encountering a type error(TypeError: unsupported operand type(s) for /: 'Point' and 'int'). Please help me understand what wrong am I doing. Below is my code:
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x=x
self.y=y
def __add__(self,right):
locx=self.x + right.x
locy=self.y + right.y
return Point(locx,locy)
def __sub__(self,right):
locx=self.x-right.x
locy=self.y-right.y
return Point(locx,locy)
def __mul__(self,right):
return self.x*right.x + self.y*right.y
def distance(self, other):
return sqrt((self.x-other.x)**2+(self.y-other.y)**2)
def __repr__(self):
return "Point(%d,%d)"%(self.x,self.y)
class Cluster(object):
def __init__(self, x, y):
self.center = Point(x, y)
self.points = []
def update(self):
temp=Point(0, 0)
#print(len(self.points))
count=0
for point in self.points:
count+=1
temp += point
print(len(self.points))
self.center = temp/count
self.points = []
def add_point(self, point):
self.points.append(point)
def compute_result(points):
points = [Point(*point) for point in points]
a = Cluster(1,0)
b = Cluster(-1,0)
a_old = []
for _ in range(10000): # max iterations
for point in points:
if point.distance(a.center) < point.distance(b.center):
# add the right point
a.add_point(point)
else:
# add the right point
b.add_point(point)
if a_old == a.points:
break
a_old = ...
a.update()
b.update()
return [(x, y)] * 2
In' Class Cluster' I have defined a 'update' method where I am trying to do' self.center = temp/count'. Thats where I am getting the error from. the error is as folows:
<ipython-input-36-56b3a700600d> in update(self)
42 temp += point
43 print(len(self.points))
---> 44 self.center = temp/count
45 self.points = []
46
TypeError: unsupported operand type(s) for /: 'Point' and 'int'
Upvotes: 0
Views: 248
Reputation: 411
It seems like the Point
class doesn't have a '/' operator for dividing a point by an integer. is Point
a class that you wrote? if so, you can just add the appropriate operator (https://www.geeksforgeeks.org/operator-overloading-in-python/ is a good starting place on how to do this). Otherwise, you will have to divide each part of the Point
object by the integer and store it back to the appropriate member variable. Something like:
temp=Point(0, 0)
count=0
for point in self.points:
count += 1
temp += point
print(len(self.points))
self.center = Point(temp.x/count, temp.y/count)
self.points = []
Upvotes: 1