编程实现求两个整数的最大公约数

铂铭 阅读:803 2024-04-25 12:54:11 评论:0

Huffman编码是一种常见的数据压缩算法,使用不同的频率来压缩数据。下面是用Python编程实现Huffman编码的一个简单示例。

```python

import heapq

from collections import defaultdict, Counter

import os

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 build_huffman_tree(text):

freq_map = Counter(text)

priority_queue = [Node(char, freq) for char, freq in freq_map.items()]

heapq.heapify(priority_queue)

while len(priority_queue) > 1:

left = heapq.heappop(priority_queue)

right = heapq.heappop(priority_queue)

merge = Node(None, left.freq right.freq)

merge.left = left

merge.right = right

heapq.heappush(priority_queue, merge)

return priority_queue[0]

def build_huffman_codes(node, current_code, huffman_codes):

if node is None:

return

if node.char is not None:

huffman_codes[node.char] = current_code

return

build_huffman_codes(node.left, current_code '0', huffman_codes)

build_huffman_codes(node.right, current_code '1', huffman_codes)

def encode_text(text, huffman_codes):

encoded_text = ''.join(huffman_codes[char] for char in text)

return encoded_text

def pad_encoded_text(encoded_text):

pad_length = 8 len(encoded_text) % 8

encoded_text = '0' * pad_length

padded_info = '{:08b}'.format(pad_length)

encoded_text = padded_info encoded_text

return encoded_text

def get_byte_array(padded_encoded_text):

if len(padded_encoded_text) % 8 != 0:

print("Encoded text not padded properly")

exit(1)

b = bytearray()

for i in range(0, len(padded_encoded_text), 8):

byte = padded_encoded_text[i:i 8]

b.append(int(byte, 2))

return b

def compress(text):

if len(text) == 0:

return "", ""

tree = build_huffman_tree(text)

huffman_codes = {}

build_huffman_codes(tree, '', huffman_codes)

encoded_text = encode_text(text, huffman_codes)

padded_encoded_text = pad_encoded_text(encoded_text)

byte_array = get_byte_array(padded_encoded_text)

return byte_array, tree

def decompress(byte_array, tree):

current = tree

decompressed_text = ''

for byte in byte_array:

bits = '{:08b}'.format(byte)

for bit in bits:

if bit == '0':

current = current.left

else:

current = current.right

if current.char is not None:

decompressed_text = current.char

current = tree

return decompressed_text

```

使用上述代码,你可以通过调用 compress 函数压缩文本,并通过调用 decompress 函数解压缩文本。在实际应用中,你可能需要将压缩后的字节流保存到文件中,并在解压缩时读取字节流进行解码。

希望这个示例能帮助你了解如何用编程实现Huffman编码。

搜索
排行榜
最近发表
关注我们

扫一扫关注我们,了解最新精彩内容