问题描述
首先,我想解释一下我所处的状况。我是一名住在法国的高中生(对不起,我的英语水平)。我的信息老师请我做一个关于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',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