2016-09-20 8 views
-5

すべてをforに変更する必要があります。どのように下のコードのためにそれを行うには?私はブロックごとに何があるのか​​についてコメントしました。なぜ地球上のPythonでループをwhileループに変換するには?

def createClusters(k, centroids, datadict, repeats): 
    for apass in range(repeats): 
    print("****PASS",apass,"****") 
    clusters = []      
    for i in range(k): 
     clusters.append([])    

    for akey in datadict:    #Creating empty list of distances 

     distances = [] 


     for clusterIndex in range(k): #Calculating the distances between data point and centroid and placing them into the list of distances. 
      dist = euclidD(datadict[akey],centroids[clusterIndex]) 
      distances.append(dist)  

     mindist = min(distances)   #centroids are recalculated 
     index = distances.index(mindist) 
     clusters[index].append(akey)  
     dimensions = len(datadict[1]) #Specifies the dimension of exam score which will be one.  

    for clusterIndex in range(k):  #Sum include the sum for each dimension of data point 
     sums = [0]*dimensions   #Sum initialized to zero 
     for akey in clusters[clusterIndex]: 
      datapoints = datadict[akey]  #Each data point will have a data key in data dictionary 
      for ind in range(len(datapoints)):   #Calculates sum of components continuously 
       sums[ind] = sums[ind] + datapoints[ind] 
     for ind in range(len(sums)):     #Calculates the average 
      clusterLen = len(clusters[clusterIndex]) 
      if clusterLen != 0:       
       sums[ind] = sums[ind]/clusterLen 

     centroids[clusterIndex] = sums #Assigning average to centroid list at proper positions 

    for c in clusters:   
     print ("CLUSTER")  #Prints all the data of clusters after each pass 
     for key in c:    
      print(datadict[key], end=" ") 
     print()      

return clusters 
+0

「すべてをforに変更する必要があります」 - なぜですか。 – TigerhawkT3

+0

あなたの現在の試み、Jainaが質問に編集したことがありますか?あなたが立ち往生している場所を絞り込むことができれば、それは回答者に大きな助けになります。 – halfer

答えて

0

あなたはwhileループにすべてforループを変換したいでしょう。
ただ、正規のforループを検討し、これは可能だろうか醜い表示する:

for i in iterable: 
    ... 

がに変わるだろう:

it = iter(iterable) 
while True: 
    try: 
     i = next(it) 
    except StopIteration: 
     break 
    ... 

醜いです!

+0

私はこれまでに変換することは決してできませんでしたが、私はしなければなりません。その任務と私は選択肢がありません。 – Jaina

関連する問題