个人认为这本书中的脚注③是欠妥的,5
和7
与6
的距离相同,何来故
之说?
根据脚注②,可以发现该例子取自维基百科:
维基百科中,它的中位数选取的是7
但这是因为其Python代码中 median = len(point_list) // 2
,使得其在偶数长度的数据集的中位数中选择了两者靠后的一个(因为数组下标从0开始)。
下附完整代码:
from collections import namedtuple
from operator import itemgetter
from pprint import pformat
class Node(namedtuple("Node", "location left_child right_child")):
def __repr__(self):
return pformat(tuple(self))
def kdtree(point_list, depth: int = 0):
if not point_list:
return None
k = len(point_list[0]) # assumes all points have the same dimension
# Select axis based on depth so that axis cycles through all valid values
axis = depth % k
# Sort point list by axis and choose median as pivot element
point_list.sort(key=itemgetter(axis))
median = len(point_list) // 2
# Create node and construct subtrees
return Node(
location=point_list[median],
left_child=kdtree(point_list[:median], depth + 1),
right_child=kdtree(point_list[median + 1 :], depth + 1),
)
def main():
"""Example usage"""
point_list = [(7, 2), (5, 4), (9, 6), (4, 7), (8, 1), (2, 3)]
tree = kdtree(point_list)
print(tree)
if __name__ == "__main__":
main()