我是 python 的新手,所以这听起来可能是一个愚蠢的问题。场景:我有一个集群类,在创建它的实例时,我为它提供了两个默认值,它们只是质心的坐标,它将是 ty
from checkbox.lib.text import split
class point:
x=0
y=0
def toString(self):
return (self.x+ ':'+self.y)
def __init__(self,a,b):
self.x=a
self.y=b
class cluster:
points=[]
centroid= point
def __init__(self,a,b):
centroid= point(a,b)
def kMeans(lis,k):
length=len(lis)
clusters=[]
for i in range(k):
clusters.append(cluster(2*i,2*i))
print clusters[i].centroid.toString()
for pt in lis:
min=10
centroidNum=0
for i in range(k):
dist=(abs(int(pt.x)- int(clusters[i].centroid.x))) +abs((int(pt.y) - int(clusters[i].centroid.y)))
if dist<min:
min=dist
centroidNum=i
clusters[centroidNum].points.append(pt)
for cl in clusters:
print "Clusters"
for pt in cl.points:
print pt.toString()
def readValues():
try:
fileHandler = open('/home/sean/input/k_means.txt', 'r')
for line in fileHandler:
tokens=split(line,",")
if len(tokens) == 2:
tempObj=point(tokens[0].strip(),tokens[1].strip())
list.append(tempObj)
except IOError:
print "File doesn't exist"
if __name__ == '__main__':
list=[]
readValues();
kMeans(list,3)
我正在尝试为质心赋值,从而传入构造函数。但我得到以下错误:
unbound method toString() must be called with point instance as first argument (got nothing instead)
我希望质心成为一个点,以便我可以访问程序的其余部分。请帮助我如何为质心赋值
输入文件具有 1,2 3,5 4,3 形式的点