我用Python 3编程Kdtree,而函数的目的是确定放入参数的节点是否在Kdtree中。
我使用递归函数,但即使存在该点也返回None。
#I put the init to show you how the kdnode is made
class KdNode:
def __init__(self, point, dim, left_child, right_child):
self.point = point;
self.dim = dim;
self.left_child = left_child;
self.right_child = right_child;
def KdTree_present(kdnode,point_to_test):
if kdnode == None:
return
else:
KdTree_present(kdnode.left_child, point_to_test)
KdTree_present(kdnode.right_child, point_to_test)
if kdnode.point == point_to_test:
return True
#Kdnode_example = [(150, 300), 1, [(200, 250), 0, None, None], [(325, 400), 0, None, None]]
即使KdTree_present的输出必须为True,也始终为None。
答案 0 :(得分:1)
点是什么类型?请记住,如果比较对象,除非它们位于相同的内存空间(它们指向相同的对象),否则总是会出错,请参考此问题Compare object instances for equality by their attributes in Python
要使==起作用,就必须重写函数__eq__
。创建该函数或将您的条件更改为类似if knode.point.x == point_to_test.x and knode.point.y == point_to_test.y
编辑:
要添加到您的评论中,递归确实存在问题,它将遍历所有子项,直到因为没有更多子项而将其返回False为止;如果找到了它,则返回True,这是更快的速度,您应该做什么是这个吗?
def KdTree_present(kdnode,point_to_test):
if kdnode == None:
return False
if kdnode.point == point_to_test:
return True
return KdTree_present(kdnode.left_child, point_to_test) or KdTree_present(kdnode.right_child, point_to_test)