Esempio n. 1
0
 def test_joined(self):
     code = ""
     for i in range(1, 1000):
         code += l_elias_encoder.encode_single_value(i)
     for i in range(1, 1000):
         decoded = l_elias_decoder.decode_single_value(code)
         code = code[len(l_elias_encoder.encode_single_value(i)) :]
         assert i == decoded
Esempio n. 2
0
def encode_header(code):
    res = unique_chars(code)
    # Total number of unique characters
    result = l_elias_encoder.encode_single_value(len(res))
    for val in res:
        # Frequency of each character
        result += l_elias_encoder.encode_single_value(res[val])
        # ASCII code of character padded to 3 digits.
        result += "{0:0=3d}".format(ord(val))
    # Total number of characters in the input file.
    result += l_elias_encoder.encode_single_value(len(code))
    return result
Esempio n. 3
0
def decode(code):
    # Calculate no of unique and remove from code.
    no_of_unique = l_elias_decoder.decode_single_value(code)
    no_of_unique_encoded = l_elias_encoder.encode_single_value(no_of_unique)
    code = code[len(no_of_unique_encoded):]

    frequencies = {}
    for i in range(no_of_unique):
        freq = l_elias_decoder.decode_single_value(code)
        freq_encoded = l_elias_encoder.encode_single_value(freq)
        code = code[len(freq_encoded):]
        char = chr(int(code[0:3]))
        code = code[3:]
        frequencies[char] = freq

    total_chars = l_elias_decoder.decode_single_value(code)
    total_chars_encoded = l_elias_encoder.encode_single_value(total_chars)
    code = code[len(total_chars_encoded):]

    heap = []
    for val in frequencies:
        node = Node(val, frequencies[val])
        heapq.heappush(heap, node)
    root = heap[0]

    while len(heap) > 1:
        min1: Node = heapq.heappop(heap)
        min2: Node = heapq.heappop(heap)
        new_node = Node(min1.char + min2.char, min1.count + min2.count)
        new_node.left = min1
        new_node.right = min2
        root = new_node

        heapq.heappush(heap, new_node)

    result = ""
    for i in range(total_chars):
        res = search_for_char(root, "", code, -1)
        result += res[1]
        code = code[len(res[0]):]

    return result
Esempio n. 4
0
 def test_all(self):
     for i in range(1, 100000):
         code = l_elias_encoder.encode_single_value(i)
         decoded = l_elias_decoder.decode_single_value(code)
         assert i == decoded
Esempio n. 5
0
 def test_from_lecture_slides(self):
     """Test using example from lecture slides."""
     expected = "00100011000110001"
     assert l_elias_encoder.encode_single_value(561) == expected