叶倩琳实验四贪心算法:Huffman编码问题实现

需积分: 0 0 下载量 31 浏览量 更新于2024-04-03 收藏 213KB DOCX 举报
实验四中,叶倩琳在2019年04月18日完成了贪心算法的任务。问题一是关于Huffman编码的实验,测试数据为:X={zhejiang university of technology,computer college} Y={1310773597218806522025}。编码实现的代码如下: ```python import heapq class Node: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def encode(root, code, data): if root is None: return if root.char: data[root.char] = code encode(root.left, code + "0", data) encode(root.right, code + "1", data) def huffman_encoding(data): pq = [Node(k, v) for k, v in data.items()] heapq.heapify(pq) while len(pq) > 1: left = heapq.heappop(pq) right = heapq.heappop(pq) internal = Node(None, left.freq + right.freq) internal.left = left internal.right = right heapq.heappush(pq, internal) root = pq[0] codes = {} encode(root, "", codes) encoded_data = "" for char in data: encoded_data += codes[char] return encoded_data, root data = {"z": 1, "h": 1, "e": 5, "j": 1, "i": 3, "a": 1, "n": 2, "g": 2, " ": 6, "u": 1, "v": 1, "r": 2, "s": 1, "t": 3, "y": 1, "o": 4, "f": 1, "c": 2, "m": 1, "p": 1, "l": 3} encoded_data, root = huffman_encoding(data) print("Encoded data:", encoded_data) ``` 以上代码实现了Huffman编码的过程,通过贪心算法构建最优编码树,并将数据进行编码。叶倩琳成功完成了这个任务,展示了她在算法实现上的能力和专业知识。