2016-09-20 4 views
-5

모든 것을 for (으)로 변경해야합니다. 아래 코드를 위해 그것을하는 방법? 나는 블록마다 무엇을하는지에 관해 논평했다.파이썬에서 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

"모든 것을 잠시 동안 변경해야합니다."- 왜? – 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

관련 문제