【问题标题】:Huffman on PythonPython 上的霍夫曼
【发布时间】:2020-08-24 18:38:28
【问题描述】:

首先,我想解释一下我所处的情况。我是一名住在法国的高中生(对不起我的英语水平)。我的信息老师要求我在 Python 中做一个压缩算法的工作。问题是我完全是这种语言的新手(以及一般的编码)。我的老师让我不要使用任何模块。

我最近给了他这个作品:


texte = "exemple"
def char_frequency(texte):
    dict = {}
    for n in texte:
        if n in dict:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict huffman = char_frequency(texte)

a = sorted(huffman.items(), key = lambda x : x[1]) 
dictio = {}

while len(a) > 1:
    noeud = ((a[0][0],a[1][0]),a[0][1]+a[1][1])
    a = [noeud]+a[2:]
    a = sorted(a, key = lambda x : x[1])

我以某种方式设法创建了“节点”,但我不知道如何将值 0 或 1 放入链接节点的“字符串”中。有人可以帮我吗?

【问题讨论】:

  • 抱歉,您提供的代码已失效

标签: python huffman-code


【解决方案1】:

你能给我们一个你预期输出的例子吗?

texte = "exemple"
def char_frequency(texte):
    dict = {}
    for n in texte:
        if n in dict:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict

huffman = char_frequency(texte)
a = sorted(huffman.items(), key = lambda x : x[1])
dictio = {}

while len(a) > 1:
    noeud = ((a[0][0],a[1][0]),a[0][1]+a[1][1])
    a = [noeud]+a[2:]
    a = sorted(a, key = lambda x : x[1])

print(noeud)
# output (('e', (('p', 'l'), ('x', 'm'))), 7)
print(a)
# output [(('e', (('p', 'l'), ('x', 'm'))), 7)]

否则 Python 中有一个函数叫做 bytearray:

exemple_string = "exemple"

# create bytearray
exemple_byte_array = bytearray(exemple_string, "utf8")

byte_list = []

# convert from binary
for byte in exemple_byte_array:
    binary_representation = bin(byte)

    byte_list.append(binary_representation)

print(byte_list)
# ['0b1100101', '0b1111000', '0b1100101', '0b1101101', '0b1110000', '0b1101100', '0b1100101']

发现这个帖子也可能有帮助:Convert string to binary in python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2023-03-23
    相关资源
    最近更新 更多