Demo entry 6776815

lzw

   

Submitted by anonymous on Dec 04, 2018 at 18:07
Language: Python 3. Code size: 703 Bytes.

def encode(input):
    #initialize dictionary
    alphabet = list(map(chr, range(0,256)))
    dict = {}
    nextFreeCode=0
    for symbol in alphabet:
        dict[symbol] = nextFreeCode
        nextFreeCode += 1
        
    curr = input.read(1)
    nextchar =  input.read(1)
    output = []
    while(nextchar):
        
        if(curr + nextchar not in dict):
            dict[curr + nextchar] = nextFreeCode
            nextFreeCode += 1
            output.append(dict[curr])
            curr = nextchar
        else:
            curr += nextchar
        
        nextchar = input.read(1) 
    
    #append last part
    output.append(dict[curr])
    return (output, dict)

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).