Huffman Tree哈夫曼树权值路径长度WPL计算

x33g5p2x  于2021-12-14 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(336)

Huffman Tree哈夫曼树(霍夫曼树、赫夫曼树)权值路径长度WPL计算

计算定义:把构建成功的哈夫曼树的每一个边缘节点(叶子)值乘以该节点到根的路径长度,最后求合。

  1. import random
  2. from binarytree import Node, get_parent
  3. def app():
  4. data = []
  5. # 生成随机测试数据。
  6. for i in range(5):
  7. d = random.randint(1, 50)
  8. data.append(d)
  9. random.shuffle(data)
  10. print(data)
  11. huffman_tree = build_huffman_tree(data)
  12. print('-----')
  13. print('最终的Huffman树')
  14. root = huffman_tree.pop()
  15. print(root)
  16. print('---')
  17. print(data)
  18. print('计算WPL')
  19. wpl(root)
  20. def build_huffman_tree(data):
  21. nodes = []
  22. for i in data:
  23. nodes.append(Node(i))
  24. print('nodes', nodes)
  25. print('开始构建Huffman树')
  26. while True:
  27. nodes = sorted(nodes, key=lambda x: x.value)
  28. # print('nodes', nodes)
  29. if len(nodes) == 1:
  30. # print('仅剩一个节点,建树结束')
  31. break
  32. left = nodes.pop(0)
  33. right = nodes.pop(0)
  34. # print('选取节点', left.value, right.value)
  35. root = Node(left.value + right.value)
  36. root.left = left
  37. root.right = right
  38. nodes.append(root)
  39. return nodes
  40. # 计算带权值路径长度WPL
  41. def wpl(root):
  42. leaves = root.leaves
  43. sum = 0
  44. for l in leaves:
  45. path = count_path(root, l)
  46. print(l.value, '->', root.value, '长度 = ', path)
  47. sum = sum + path * l.value
  48. print('带权值路径长度WPL =', sum)
  49. def count_path(root, node):
  50. root_value = root.value
  51. count = 0
  52. while True:
  53. p = get_parent(root, node)
  54. count = count + 1
  55. if p.value == root_value:
  56. break
  57. else:
  58. node = p
  59. return count
  60. if __name__ == '__main__':
  61. app()

输出:

  1. [18, 35, 40, 3, 9]
  2. nodes [Node(18), Node(35), Node(40), Node(3), Node(9)]
  3. 开始构建Huffman
  4. -----
  5. 最终的Huffman
  6. _105_____________
  7. / \
  8. 40 ____65
  9. / \
  10. ___30 35
  11. / \
  12. 12 18
  13. / \
  14. 3 9
  15. ---
  16. [18, 35, 40, 3, 9]
  17. 计算WPL
  18. 40 -> 105 长度 = 1
  19. 35 -> 105 长度 = 2
  20. 18 -> 105 长度 = 3
  21. 3 -> 105 长度 = 4
  22. 9 -> 105 长度 = 4
  23. 带权值路径长度WPL = 212

相关文章