1

First, I would like to explain the situation I'm in. I'm a high schooler living in France (sorry for my English level). I was asked by my info teacher to do a work on a compression algorithm in Python. The issue is that I'm a total newbie in this language (and in coding in general). My teacher asked me not to use any modules.

I recently gave him this work:


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])

I somehow managed to create "nodes" but I don't know how to put a value of 0 or 1 to the "string" linking the nodes. Can someone help me?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
lizantros
  • 19
  • 1

1 Answers1

0

Can you give us an exemple of your expected output?

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)]

Othewise there is a function in Python called 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']

Found this thread also that might be helpful: Convert string to binary in python

rblais
  • 26
  • 2