2017-10-16 6 views
1

特定の点の最近傍点を返した後、次に近い点を別の点に戻すときに、前と同じ最も近い点が返されます。何故ですか?最も近いポイントは、ツリー内の全体の異なる場所に等しいなぜですか?

class kdnode: 
    def __init__(self,point,left,right): 
     self.point = point 
     self.left = left 
     self.right = right 

class kdTree: 
    def __init__(self,points,threshold): 
     self.threshold = threshold 
     self.root = self.make_kdtree(points) 
     self.froot = None 
     self.isFirst = True 

    def make_kdtree(self,points,depth = 0): 
     if(len(points) <= self.threshold): 
      return kdnode(points,None,None) 
     dimension = 2 
     axis = depth % dimension 
     sp = sorted(points,key = lambda point:point[axis]) 
     mid = len(points)//2 
     return kdnode(sp[mid],self.make_kdtree(sp[:mid],depth+1),self.make_kdtree(sp[mid+1:],depth+1)) 

    def find_closest(self,point,depth=0): 
     if self.isFirst: 
      self.froot = self.root.point 
      self.isFirst = False 
     if(self.root.left) is None and self.root.right is None: 
      return self.root.point 
     axis = depth%2 
     if point[axis] > self.root.point[axis]: 
      self.root = self.root.right 
     else: 
      self.root = self.root.left 
     return self.find_closest(point,depth+1) 

答えて

0

これが理由です:find_closest()が呼び出されると

def find_closest(self,point,depth=0): 
    if self.isFirst: 
     self.froot = self.root.point 
     self.isFirst = False 

、それ自体を変更します。これは間違いなくあなたが望むものではありません。 find_closest()は、データ構造を破壊しない読み取り専用操作でなければなりません。

+0

ありがとうございます。しかし、あなたはそれをもっとはっきりと説明できますか? –

+0

'self'は現在のオブジェクトです。 'self.isFirst = False'は現在のオブジェクトを変更します。次にfind_closest()を呼び出すと、変更したので同じではありません。 – remram

関連する問題