python 코딩 에러..
글쓴이: skyline066 / 작성시간: 월, 2017/04/10 - 1:21오전
타임 함수를 빼면 잘돌아가는데 타임함수를 넣으면 오류가 딱 나버리네요..후....어떻게 수정하는게 좋을까요..
# ver 1.5 import time import random from math import sqrt class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "Point(%.2f, %.2f)"%(self.x, self.y) def __repr__(self): return self.__str__() def dist ( p1, p2 ): if ( p1 and p2 ): d = sqrt( (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) ) return d return float('inf') def distPair( pair ): if (pair[0] and pair[1]): return dist(pair[0], pair[1]) return float('inf') def pivotSplit(S, left, p, right, descend=False, f=lambda a,b : a>=b ): S[p], S[left] = S[left], S[p] i = left + 1 j = right while ( i <= j ) : while ( i <= j and ( ( descend==False and f(S[left], S[i]) ) or (descend == True and f(S[i], S[left]) ) )): i = i + 1 while ( i <= j and ( ( descend==False and f(S[j], S[left]) ) or (descend == True and f(S[left], S[j]) ) ) ) : j = j - 1 if ( i < j ) : S[i], S[j] = S[j], S[i] i = i + 1 j = j - 1 new_p = i - 1 S[left], S[new_p] = S[new_p], S[left] return new_p def quickSort(S, left=0, right=-2, descend=False, f=lambda a,b:a>=b): if right == -2 : right = len(S)-1 # right 인자가 생략되면, 맨끝의 항목의 인덱스로 처리. if (left < right ) : p = int( (left + right) / 2 ) p = pivotSplit(S, left, p, right, descend, f) quickSort(S, left, p-1, descend, f ) quickSort(S, p+1, right, descend, f ) def fastClosestPair(S) : def closestPairInThreePairs( pair1, pair2, pair3 ) : d1 = dist(pair1[0], pair1[1]) d2 = dist(pair2[0], pair2[1]) d3 = dist(pair3[0], pair3[1]) if d1 < d2 and d1 < d3 : return pair1 elif d2 < d1 and d2 < d3 : return pair2 else : return pair3 def closestPairInCenter(S_left, S_right, d): def extractCenterRegionInSLeft(S, d) : theMostRight_In_S = S[-1] for i in range( -1 , -len(S)-1, -1) : if abs(theMostRight_In_S.x-S[i].x) > d : return S[i+1:] return S[:] def extractCenterRegionInSRight(S, d) : theMostLeft_In_S = S[0] for i in range(0, len(S), 1) : if abs(theMostLeft_In_S.x-S[i].x) > d : return S[0:i] return S[:] S_CLD = extractCenterRegionInSLeft(S_left, d) S_CRD = extractCenterRegionInSRight(S_right, d) quickSort(S_CLD, f=lambda a,b:a.y>=a.y) quickSort(S_CRD, f=lambda a,b:a.y>=b.y) #print("S_centerLeft : ", S_centerLeft) #print("S_centerRight: ", S_centerRight) min_i = min_j = -1 min_d = d for i in range(0, len(S_CLD)): for j in range(0, len(S_CRD)): dij = dist(S_CLD[i], S_CRD[j]) if dij < min_d : min_i = i min_j = j min_d = dij if ( min_i >= 0) : #print( S_CLD[min_i], S_CRD[min_j], "d:", min_d) return (S_CLD[min_i], S_CRD[min_j]) else: return (None, None) def closestPair(S) : i = len(S) if i == 0 : return (None, None) elif i == 1 : return (S[0], None) elif i == 2 : return (S[0], S[1]) elif i == 3 : return closestPairInThreePairs( (S[0], S[1]), (S[1], S[2]), (S[0], S[2]) ) half_i = int(i / 2 + 0.5) S_left = S[0:half_i] S_right = S[half_i:] #print ("Split: ", S_left, S_right) cp_left = closestPair(S_left) cp_right = closestPair(S_right) d = min(distPair(cp_left), distPair(cp_right) ) #print ("d : ", d) cp_center = closestPairInCenter(S_left, S_right, d) #print ("cp_center", cp_center, "cp_d : ", distPair(cp_center)) return closestPairInThreePairs(cp_left, cp_center, cp_right) S1 = S[:] #print (S1) quickSort(S1, f=lambda a,b:a.x>=b.x) #print ("After Sort_in_X :", S1) return closestPair(S1) def simpleClosestPair(S): # Compare all pairs and find the cloest pair min_d = sqrt(box_h*box_h + box_w*box_w) for i in range(0, len(S)): for j in range(0, i): #print (int(dist( S[i], S[j] )), end=', ' ) d = dist( S[i], S[j] ) if d < min_d : min_d = d min_i = i min_j = j #print () #print ("cloest Pair: ", S[min_i], S[min_j]) #print ("closest distance = ", min_d ) return ( S[min_i], S[min_j] ) def generateRandomPoints(width, height, n): from random import random S = [] for i in range(n): p = Point( random() * width , random() * height ) S.append(p) return S box_w = 500 box_h = 300 def simpleTest(): S = generateRandomPoints(box_w, box_h, 10) print () print ("Points List : ", end='') print (S) print () cp = fastClosestPair(S) print ("Fast Closest Pair: ", end='') print (cp) print ("Closest distance : %.2f"%distPair(cp)) print () cp1 = simpleClosestPair(S) print ("Simple Closest Pair: ", end='') print (cp1) print ("Closest distance : %.2f"%distPair(cp1)) print () def timeExperiment(rep): print ("==============================================") for n in [10, 100, 1000, 10000] : print ("size of list : ", n) # n개의 무작위 수를 자동 추가 init_A = [] for i in range(n): init_A.append(random.random()) sum_elapsed_time1 = 0 sum_elapsed_time2 = 0 for repetition in range(rep) : A = init_A[:] k = random.randint(1, n) sA = A[:] t1 = time.process_time() k_selected_element1 = simpleClosestPair(sA) elapsed_time1 = time.process_time() - t1 sum_elapsed_time1 = sum_elapsed_time1 + elapsed_time1 t2 = time.process_time() k_selected_element2 = fastClosestPair(A) elapsed_time2 = time.process_time() - t2 sum_elapsed_time2 = sum_elapsed_time2 + elapsed_time2 print ("Execution Time for simple selection algorithm : %.4f sec"%sum_elapsed_time1) print ("--------------------------------------------") print ("Execution Time for faster selection algorithm : %.4f sec"%sum_elapsed_time2) print ("==============================================") if __name__=='__main__': simpleTest() timeExperiment(100)
Forums:
Show your error message.
Show your error message.
세벌 https://sebuls.blogspot.kr/
타임함수가 문제인거같은데...
타임함수가 문제인거같은데...
error message
Traceback (most recent call last):
File "C:\Users\SAMSUNG\Desktop\ch03_closestpair_v15.py", line 213, in
timeExperiment(100)
File "C:\Users\SAMSUNG\Desktop\ch03_closestpair_v15.py", line 195, in timeExperiment
k_selected_element1 = simpleClosestPair(sA)
File "C:\Users\SAMSUNG\Desktop\ch03_closestpair_v15.py", line 137, in simpleClosestPair
d = dist( S[i], S[j] )
File "C:\Users\SAMSUNG\Desktop\ch03_closestpair_v15.py", line 18, in dist
d = sqrt( (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) )
AttributeError: 'float' object has no attribute 'x'
sol
generateRandomPoints함수로 투플정의하셔야합니다
요건 잘돌아가요
소스 정독하고 질문하세요.
두개의 소스는 완전 다른소스입니다.
시간측정함수가 어떤 투플을 소팅하는지가 다릅니다
처음주신소스는 인자가 두개고 뒤에주신건 하나입니다.
그러니까 투플정의부분이 달라야합니다
그냥 받아오신소스 복붙해서 답찾지마시고 읽어보세요
댓글로 단건 제가짠거고 질문한게 구한코딩에 시간을
댓글로 단건 제가짠거고 질문한게 구한코딩에 시간을 재볼려고 한거에요..ㅠ
학교에서 분할정복 알고리즘으로 짠거랑 좀더 빠르게 코딩해서 짠거랑 시간비교를 했을때 빠르게 코딩한걸 쓰는이유가있다고해서 한번 재보는거에요..ㅠ
근데 질문한코드를 제가 안짜서 그런지몰라도 타임함수를 어떻게 넣어야할지 잘모르겠네요..죄송합니다..
.
init_A = []
for i in range(n):
init_A.append(random.random())
부분을
S = generateRandomPoints(box_w, box_h, n)로 바꾸시고,
그에따라 밑에 코드 약간만 수정되면 잘돌아가겠네요
와!!!와!!!!! 성공했어요!!!!!!!!!!!!!
와!!!와!!!!! 성공했어요!!!!!!!!!!!!!!
이렇게 간단한거였다니!!!!!!!!!!!!!!!!!!!!!!!!!아아아아아아아아
너무감사합니다 가슴이 뻥뚤리네요 정말 감사합니다!!!!!!!!!!!!!!!!!!!!!!!!
-
네 과제열심히하세요~
댓글 달기