Huffman coding: Difference between revisions
Content added Content deleted
(Alternative Python) |
m (Python: pretty print Huffman table) |
||
Line 5,707: | Line 5,707: | ||
s = "this is an example for huffman encoding" |
s = "this is an example for huffman encoding" |
||
data = s.encode() # Need a byte string |
data = s.encode() # Need a byte string |
||
⚫ | |||
# Pretty print the Huffman table |
|||
print(f"Symbol Code\n------ ----") |
|||
for k, v in sorted(huffman_table(tree).items(), key=lambda x: len(x[1])): |
|||
print(f"{chr(k):<6} {v}") |
|||
# Print the bit pattern of the encoded data |
# Print the bit pattern of the encoded data |
||
⚫ | |||
print("".join(_bits_from_bytes(encoded))) |
print("".join(_bits_from_bytes(encoded))) |
||
Line 5,723: | Line 5,728: | ||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Symbol Code |
|||
------ ---- |
|||
n 000 |
|||
110 |
|||
m 0010 |
|||
h 0101 |
|||
i 1001 |
|||
f 1010 |
|||
e 1011 |
|||
a 1110 |
|||
r 00110 |
|||
l 00111 |
|||
c 01000 |
|||
u 01001 |
|||
x 01100 |
|||
d 01101 |
|||
t 01110 |
|||
p 01111 |
|||
Ā 10000 |
|||
g 10001 |
|||
o 11110 |
|||
s 11111 |
|||
011100101100111111110100111111110111000011010110110011100010011110011110111101010111100011011001010100110101010001011100001101011000010001111001101100100010001100000000 |
011100101100111111110100111111110111000011010110110011100010011110011110111101010111100011011001010100110101010001011100001101011000010001111001101100100010001100000000 |
||
this is an example for huffman encoding |
this is an example for huffman encoding |