In [1]:
#! /usr/bin/python

In [80]:
def read_file ( filename ):
    all_strings = []
    with open(filename) as f:
        for linen in f:
            all_strings.append(linen.rstrip('\n'))
    return ( all_strings )

def decode ( string ):
    hex = "0123456789abcdef"
    new_string = ""
    i = 0
    while i < len(string):
        if (string[i] == '\\') and (string[i+1] == 'x' and (string[i+2] in hex) and (string[i+3] in hex)):
            new_string = new_string + chr(int(string[i+2] + string[i+3], 16))         # add one \ for every two \\
            i += 3
        
        elif (string[i] != '\\') and (string[i] != '\"'): 
            new_string = new_string + string[i]           # add everything that is not a \ or "
        
        elif (string[i] == '\\') and (string[i+1] == '\\'):
            new_string = new_string + string[i+1]         # add one \ for every two \\
            i += 1

        elif (string[i] == '\\') and (string[i+1] == '\"'):
            new_string = new_string + string[i+1]         # add one " for every  \"
            i += 1
        i += 1
    return new_string

def encode ( string ):
    hex = "0123456789abcdef"
    new_string = "\""
    i = 0
    while i < len(string):
        if (string[i] == '\\') or (string[i] == '\"'):
            new_string = new_string + "\\" + string[i]
        else:
            new_string = new_string + string[i]
        i += 1
    new_string = new_string + "\""
    return new_string

In [81]:
filename = './input'
all_strings = read_file ( filename )

literals_count = 0
decode_count = 0
encode_count = 0

# decode
for i in all_strings:
    decode_str = decode(i)
    encode_str = encode(i)
    literals_count += len(i)
    decode_count += len(decode_str)
    encode_count += len(encode_str)
#    print ("literal: {0:50s} - decode: {1:50s}".format(i, decode_str))
#    print ("literal: {0:50s} - encode: {1:50s}".format(i, encode_str))

In [79]:
print ("Star 1:")
print ("literals:    {0:8d}          - decoded: {1:8d}".format(literals_count, decode_count))
print ("decode char: {0:8d}".format(literals_count-decode_count))
print ("--\nStar 2:")
print ("literals:    {0:8d}          - encoded: {1:8d}".format(literals_count, encode_count))
print ("encode char: {0:8d}".format(encode_count-literals_count))


Star 1:
literals:        6489          - decoded:     5118
decode char:     1371
--
Star 2:
literals:        6489          - encoded:     8606
encode char:     2117

In [ ]:


In [ ]: