2016-11-23 7 views
0

나는 알고리즘을 작성하려고하는데 바로 기본적인 단계에있다.Keyerror : 1 python

import numpy as np 

import random 

X = [2,3,5,8,12,15,18] 

C = 2 

def rand_center(ip,C): 

    centers = {} 
    for i in range (C): 
     if i>0: 
      while centers[i] != centers[i-1]: 
       centers[i] = random.choice(X) 
       else: 
      centers[i] = random.choice(X) 
    return centers 
    print (centers) 

rand_center(X,C) 

내가 이것을 실행, 그것은 나를 KeyError를 제공합니다 : 1
은 누구도 날이 오류를 해결 안내 할 수
코드는 무작위로 클러스터링을위한 센터를 선택하기 위해 다음과 같다?

+1

그런데 그 반환 문장 다음에 인쇄 할 수 없습니다 (또는 무엇이든 할 수 없습니다). –

답변

1

while centers[i] != centers[i-1] ... for i in range (C): 루프의 두 번째 반복은 어떻게됩니까?

centers[1] != centers[0] ... 그 시점에서 centers[1]이 없습니다.

0

이 문제는 배열에 대한 잘못된 색인 때문일 것으로 생각됩니다. 배열에 전달 된 인덱스를 다시 확인하면이 문제를 해결하는 데 도움이 될 수 있습니다. 이 오류가 발생하는 행 번호를 게시하면 코드를 디버깅하는 것이 더 도움이됩니다. 예 :

0

코드는

import numpy as np 
import random 

X = [2,3,5,8,12,15,18] 

C = 2 

def rand_center(ip,C): 
    if C<1: 
     return [] 
    centers = [random.choice(ip)] 
    for i in range(1,min(C,len(ip))): 
     centers.append(random.choice(ip)) 
     while centers[i] in centers[:i]: 
      centers[i] = random.choice(ip)   
    return centers 

print (rand_center(X,C)) 
+0

모두 감사합니다! – leo

0

난 당신이 출력 찾고 희망을 다음과 같이 쓰기 다시해야 잘못된 것입니다. 현재 키, 이전 및 다음 키에 동일한 값이없는 키와 값 이있는 사전입니다.

import numpy as np 
import random 

X = [2,3,5,8,12,15,18] 
C = 2 

def rand_center(ip,C): 
    centers = {} 
    for i in range (C): 
     rand_num = random.choice(X) 
     if i>0: 
      #Add Key and Value in Dictionary. 
      centers[i] = rand_num 
      #Check condition if it Doesn't follow the rule, then change value and retry. 
      while rand_num != centers[i-1]: 
       centers[i] = rand_num 
       #Change the current value 
       rand_num = random.choice(X) 
     else: 
      #First Key 0 not having previous element. Set it as default 
      centers[i] = rand_num 
    return centers 

print"Output: ",rand_center(X,C)