2020数据结构小学期(二)——哈夫曼编码算法
2、哈夫曼编码算法
输入:字符及其权值,待译码字符串,待解码字符串
功能要求:输出各字符的哈夫曼编码,输出译码字符串,输出解码字符串
源码:
1 class Node: 2 def __init__(self, name, weight): 3 self.name = name 4 self.weight = weight 5 self.left = None 6 self.right = None 7 self.father = None 8 9 def is_left_child(self): 10 return self.father.left == self 11 12 13 def create_prim_nodes(data_set, labels): 14 if len(data_set) != len(labels): 15 raise Exception('数据和标签不匹配!') 16 nodes = [] 17 for i in range(len(labels)): 18 nodes.append(Node(labels[i], data_set[i])) 19 return nodes 20 21 22 def create_HF_tree(nodes): 23 tree_nodes = nodes.copy() 24 while len(tree_nodes) > 1: 25 tree_nodes.sort(key=lambda node: node.weight) 26 new_left = tree_nodes.pop(0) 27 new_right = tree_nodes.pop(0) 28 new_node = Node(None, (new_left.weight + new_right.weight)) 29 new_node.left = new_left 30 new_node.right = new_right 31 new_left.father = new_right.father = new_node 32 tree_nodes.append(new_node) 33 tree_nodes[0].father = None 34 return tree_nodes[0] 35 36 37 def get_huffman_code(nodes): 38 codes = {} 39 for node in nodes: 40 code = '' 41 name = node.name 42 while node.father != None: 43 if node.is_left_child(): 44 code = '0' + code 45 else: 46 code = '1' + code 47 node = node.father 48 codes[name] = code 49 return codes 50 51 52 def encode_huffman(codes, str_encoding): 53 after_encoding = '' 54 for char in str_encoding: 55 flag = 0 56 for key in codes.keys(): 57 if char == key: 58 after_encoding += codes[key] 59 flag = 1 60 break 61 if flag == 0: 62 print('字符串中包含未知字符!') 63 break 64 return after_encoding 65 66 67 def decode_huffman(codes, str_decoding): 68 after_decoding = '' 69 temp = '' 70 for char in str_decoding: 71 temp += char 72 if temp == str_decoding: 73 print("编码存在错误!") 74 break 75 for key in codes.keys(): 76 if codes[key] == temp: 77 after_decoding += key 78 temp = '' 79 return after_decoding 80 81 82 if __name__ == '__main__': 83 # labels = ['a', 'b', 'c', 'd', 'e', 'f'] 84 # data_set = [9, 12, 6, 3, 5, 15] 85 str_labels = input('请输入字符(用空格分隔):') 86 str_data = input('请输入权值(用空格分隔):') 87 str_labels = str_labels.replace(' ', '') 88 list_data = str_data.split(' ') 89 labels = [] 90 data_set = [] 91 for char in str_labels: 92 labels.append(char) 93 for list in list_data: 94 data_set.append(int(list)) 95 96 # str_encoding = 'abbcefd' 97 # str_decoding = '0001011001011111010' 98 str_encoding = input('请输入译码字符串:') 99 str_decoding = input('请输入解码字符串:') 100 nodes = create_prim_nodes(data_set, labels) 101 root = create_HF_tree(nodes) 102 codes = get_huffman_code(nodes) 103 print('各字符的哈夫曼编码:') 104 for key in codes.keys(): 105 print(key, ': ', codes[key]) 106 107 print('译码字符串:', encode_huffman(codes, str_encoding)) 108 print('解码字符串:', decode_huffman(codes, str_decoding))