def kmeans(examplesexampletypekverbose)"""assumes examples is list of examples of type exampletypek is positive intverbose is boolean returns list containing clusters if verbose is true it prints result of each iteration of -means""#get randomly chosen initial centroids initialcentroids random sample(examplesk#create singleton cluster for each centroid clusters [for in initialcentroidsclusters append(cluster([ ]exampletype)#iterate until centroids do not change converged false numiterations while not convergednumiterations + #create list containing distinct empty lists newclusters [for in range( )newclusters append([]#associate each example with closest centroid for in examples#find the centroid closest to smallestdistance distance(clusters[ getcentroid()index for in range( )distance distance(clusters[igetcentroid()if distance smallestdistancesmallestdistance distance index #add to the list of examples for the appropriate cluster newclusters[indexappend( #upate each clustercheck if centroid has changed converged true for in range(len(clusters))if clusters[iupdate(newclusters[ ] converged false if verboseprint 'iteration #str(numiterationsfor in clustersprint print '#add blank line return clusters figure -means clustering figure contains functiontrykmeansthat calls kmeans multiple times and selects the result with the lowest dissimilarity