请为以下代码注释:# 构建哈夫曼树 def build_tree(freq): heap = [[weight, [symbol, ""]] for symbol, weight in freq.items()] heapq.heapify(heap) while len(heap) > 1:# 节点长大于1 lo = heapq.heappop(heap) hi = heapq.heappop(heap) for pair in lo[1:]: pair[1] = '0' + pair[1] for pair in hi[1:]: pair[1] = '1' + pair[1] heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) return sorted(heapq.heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
时间: 2024-04-28 18:22:13 浏览: 83
huffman.rar_Huffman tree_hfmTree_huffman 编码 译码 _哈夫曼_哈夫曼树
4星 · 用户满意度95%
# 构建哈夫曼树
# freq 是一个字典,键为符号,值为该符号出现的频率
def build_tree(freq):
# 将 freq 转换为堆 heap,每个元素是 [weight, [symbol, ""]] 的形式
heap = [[weight, [symbol, ""]] for symbol, weight in freq.items()]
# 将 heap 转换为小根堆
heapq.heapify(heap)
# 当堆中节点数大于1时,不断取出两个最小的节点构建一个新节点,直到只剩下一个节点,即根节点
while len(heap) > 1:
lo = heapq.heappop(heap) # 取出权值最小的节点 lo
hi = heapq.heappop(heap) # 取出权值次小的节点 hi
# 将 lo 中每个元素的编码加上'0',表示该节点是左子树
for pair in lo[1:]:
pair[1] = '0' + pair[1]
# 将 hi 中每个元素的编码加上'1',表示该节点是右子树
for pair in hi[1:]:
pair[1] = '1' + pair[1]
# 将新节点 [lo[0] + hi[0]] + lo[1:] + hi[1:] 插入堆 heap 中
heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
# 返回根节点的左右子树,按编码长度从小到大排序
return sorted(heapq.heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
阅读全文