我是班级工作的新手,更具体地说,是四叉树。我看了一个从here提取的四叉树的基本示例。
启动四叉树时,无法识别任何方法,我也不知道问题是源于原始代码还是因为我执行错误。
这是我从已经提到的网站复制的一些代码:
#Tree initialization
class QTree():
def __init__(self, k, n): #Maximum number of points in a node (threshold) and points existing (n)
self.treshold = k
self.points = [Point(random.uniform(0, 10), random.uniform(0, 10)) for x in range(n)] #Generation of n points
self.root = Node(0, 0, 10, 10, self.points)
def add_point(x,y):
return Point(x,y)
def get_points(self):
return self.points
def subdivide(self):
recursive_subdivide(self.root,self.threshold)
def graph(self):
fig = plt.figure(figsize=(12, 8))
plt.title("Quadtree")
ax = fig.add_subplot(111)
c = find_children(self.root)
print "Number of segments: %d" %len(c)
areas = set()
for el in c:
areas.add(el.width*el.height)
for n in c:
ax.add_patch(patches.Rectangle((n.x0, n.y0), n.width, n.height,
fill=False))
x = [point.x for point in self.points]
y = [point.y for point in self.points]
plt.plot(x, y, 'ro')
plt.show()
return
def recursive_subdivide(node,k):
if len(node.points)<=k:
return
w_ = float(node.width/2)
h_ = float(node.height/2)
p = contains(node.x0, node.y0, w_, h_, node.points)
x1 = Node(node.x0, node.y0, w_, h_, p ) #The new node (x1) will only contain the points that are within the node's limits
recursive_subdivide(x1,k)
p = contains(node.x0, node.y0+h_, w_, h_, node.points)
x2 = Node(node.x0, node.y0+h_, w_, h_, p)
recursive_subdivide(x2, k)
p = contains(node.x0+w_, node.y0, w_, h_, node.points)
x3 = Node(node.x0 + w_, node.y0, w_, h_, p)
recursive_subdivide(x3, k)
p = contains(node.x0+w_, node.y0+w_, w_, h_, node.points)
x4 = Node(node.x0+w_, node.y0+h_, w_, h_, p)
recursive_subdivide(x4, k)
node.children = [x1, x2, x3, x4]
def contains(x, y, w, h, points): #Select all the points that are inside the node´s limits
pts = []
for point in points:
if point.x >= x and point.x <= x+w and point.y>=y and point.y<=y+h:
pts.append(point)
return pts
def find_children(node):
if not node.children:
return [node]
else:
children = []
for child in node.children:
children += (find_children(child))
return children
这样做之后:
q=QTree(3,200) #Threshold = 3, Number of points = 200
q.graph()
我总是遇到相同的错误: “ NameError:名称'find_children'未定义”。 显然,启动Tree时没有一种方法可以识别。
可能是什么问题?我如何正确执行这样的树?