[英]Huffman on Python
首先,我想解释一下我所处的情况。我是一名住在法国的高中生(抱歉我的英语水平)。 我的信息老师让我在 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 的值添加到链接节点的“字符串”中。 有人能帮我吗?
你能给我们一个你预期输出的例子吗?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.