Пример #1
0
def compress():
    """Reads a sequence of 8-bit bytes from standard input; compresses them using
    Huffman codes with an 8-bit alphabet; and writes the results to standard
    input."""
    s = BinaryStdIn.read_string()
    # Tabulate frequency counts
    freq = [0 for i in range(0, _R)]
    for i in range(0, len(s)):
        freq[ord(s[i])] += 1
    # Build Huffman trie
    root = _build_trie(freq)
    # Build code table
    st = [None for i in range(0, _R)]
    _build_code(st, root, "")
    # Print trie for decoder
    _write_trie(root)
    # Print number of bytes in original uncompressed message
    BinaryStdOut.write_int(len(s))
    # Use Huffman code to encode input
    for i in range(0, len(s)):
        code = st[ord(s[i])]
        for j in range(0, len(code)):
            if code[j] == "0":
                BinaryStdOut.write_bool(False)
            elif code[j] == "1":
                BinaryStdOut.write_bool(True)
            else:
                raise ValueError("Illegal state")
    BinaryStdOut.close()
Пример #2
0
def compress():
    """Reads a sequence of 8-bit bytes from standard input; compresses them using
    LZW compression with 12-bit codewords; and writes the results to standard
    output."""
    input_ = BinaryStdIn.read_string()
    st = TST()
    for i in range(0, _R):
        st.put("" + chr(i), i)
    code = _R + 1
    while len(input_) > 0:
        s = st.longest_prefix_of(input_)
        BinaryStdOut.write_int(st.get(s), _W)
        t = len(s)
        if t < len(input_) and code < _L:
            st.put(input_[0 : t + 1], code)
            code += 1
        input_ = input_[t:]
    BinaryStdOut.write_int(_R, _W)
    BinaryStdOut.close()