## L303 / Solution
## SXD

''' 
Consider the following binary encoding of the alphabet A = {'a', 'b', 'c', 'd', 'e'}: 
'a' → '0', 'b' → '11', 'c'→ '100', 'd' → '1010', 'e' → '1011'.
'''
R = [('a','0'), ('b','11'), ('c','100'), ('d','1010'), ('e','1011')]

# encoding dictionary
x2c = dict(R)

# decoding dictionary
c2x = dict([(c,x) for x, c in R])


''' 1.
Define a function E(X) that yields, given a message X in the alphabet A, 
the encoded message. For example, E("aac") should yield '001011'.
'''

def E(X):
    C = ''
    for x in X:
        C += x2c[x]
    return C 
    
''' 2.
Generate a random message X of length 50 (say) in the alphabet A 
with expected frequences 50, 20, 15, 10 and 5 for the characters 
'a', 'b', 'c', 'd', 'e' and find the coded message C.
'''
n = 50
U = 50*'a'+20*'b'+15*'c'+10*'d'+5*'e'
L = rd_choice(U, n)
X = ''
for x in L:
    X += x
C = E(X)

''' 3.
In an ASCII-like encoding the message X requires at least 3 bits per character. 
Find how many bits per character are needed for the encoding C. 
What is the compression ratio?
'''
cf = len(C)/(3*len(X))

''' 4.
Define a function D(C) that yields, given an encoded message C, 
the original message X. Test it with the C obtained in the previous point.
'''
def D(C):
    X = ''
    while len(C):
        c = ''
        while not c in c2x:
            c += C[0]
            C = C[1:]
        X += c2x[c]
    return X
  
  
  
  
  
  
  
    

