这段代码不是我写的。我试图从中画出一棵霍夫曼树,但我想要父节点的值并将它们放在一个带有二进制代码的列表中。我怎样才能做到这一点?
import heapq
from collections import defaultdict
def encode(frequency):
heap = [[weight, [symbol, '']] for symbol, weight in frequency.items()]
heapq.heapify(heap)
while len(heap) > 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))
data="ALL PEOPLE SEEM TO NEED DATA PROCESSING."
frequency = defaultdict(int)
for symbol in data:
frequency[symbol] += 1
huff = encode(frequency)
print ("Symbol".ljust(10) + "Weight".ljust(10) + "Huffman Code")
for p in huff:
print(p[0].ljust(10) + str(frequency[p[0]]).ljust(10) + p[1])
使用 Turtle 链接到 Huffman 树的图像:https ://imgur.com/a/Ql0QIDD