【问题标题】:How to calculate length of each Huffman code?如何计算每个霍夫曼码的长度?
【发布时间】:2021-06-16 16:10:56
【问题描述】:

代码的输出看起来像这样我如何计算代码的长度让我们说我得到了 Huffman 长度 1,10,11 现在我如何计算每个代码的长度以便我得到 {1,2,2}。 我试图打印一些东西,但它只打印最后一个 (11)。

 Char | Huffman code 
----------------------
 'P_0' |           1
 'P_1' |          10
 'P_2' |          11

代码在此链接https://www.section.io/engineering-education/huffman-coding-python/

【问题讨论】:

  • 你能提供只打印最后一个的代码吗?如果我正确理解您想要什么,您只需将倒数第二行中的 huffman_code[id] 包装到 len() 调用中。
  • 是的。print(huffman_code[id])
  • print(len(huffman_code[id])) 但将其保留在 for 循环中。
  • 当我这样做时,它只是给了我最后一个的长度。我想将这些长度存储在一个数组中。
  • Stackoverflow 不是免费的编码服务。

标签: python huffman-code


【解决方案1】:

在文件底部添加:

lengths = tuple(len(huffman_code[id]) for id in range(len(freq)))
print(lengths)

输出:

Enter the string to compute Huffman Code: bar
 Char | Huffman code 
----------------------
 'b'  |           1
 'a'  |          00
 'r'  |          01
Average length of the code: 1.650000
(1, 2, 2)

我收到(1, 2, 2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多