Guest User

[7/18/2014] Challenge #171 [Hard] Intergalatic Bitstream

a guest
Jul 19th, 2014
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. '''http://www.reddit.com/r/dailyprogrammer/comments/2b21mp/7182014_challenge_171_hard_intergalatic_bitstream/'''
  2. import math
  3. import sys
  4.  
  5. CHARS = ' EOTRASINMDGHLPY0BF1CKUWV39254768JQXZ' # sorted by most common
  6. N = 4 # number of bits each group will use
  7.  
  8. # create maps for compressing and decompressing
  9. comp_map = {}
  10. group_chars = int(math.pow(2,N))-1 # how many chars each group can hold
  11. group_prefix = '{i:b}'.format(i=group_chars) # use 1111 as the prefix
  12. for i,c in enumerate(CHARS):
  13.     quot = i/group_chars
  14.     rem = i%group_chars
  15.     comp_map[c] = '{q}{r}'.format(q=group_prefix*quot,
  16.                                   r='{:b}'.format(rem).zfill(N))
  17. decomp_map = dict((v,k) for k, v in comp_map.iteritems())
  18.  
  19. def compress(msg):
  20.     '''compress a message to a string of 1 and 0s'''
  21.     output = []
  22.     for c in msg:
  23.         output.append(comp_map[c])
  24.     return ''.join(output)
  25.  
  26. def decompress(msg):
  27.     '''decompress a string of 1 and 0s back to the original message'''
  28.     output = []
  29.     chunks = [ msg[i:i+N] for i in xrange(0, len(msg), N)]
  30.     prefix = ''
  31.     for c in chunks:
  32.         if c==group_prefix:
  33.             prefix = prefix+c
  34.         else:
  35.             output.append(decomp_map[prefix+c])
  36.             prefix = ''
  37.     return ''.join(output)
  38.  
  39. if __name__ == '__main__':
  40.     msg = sys.argv[1]
  41.     msg_len = len(msg)*8
  42.     print 'Read Message of {x} Bits.'.format(x=msg_len)
  43.     print 'Message:{}'.format(msg)
  44.  
  45.     comp_msg = compress(msg)
  46.     comp_msg_len = len(comp_msg)
  47.     print 'Compressing {x} Bits into {y} Bits. ({z}pc compression)'.format(
  48.                                 x=msg_len,
  49.                                 y=comp_msg_len,
  50.                                 z=int(100*float(msg_len-comp_msg_len)/msg_len))
  51.     print 'Compressed Message:{}'.format(comp_msg)
  52.  
  53.     print 'Sending Message.'
  54.  
  55.     decomp_msg = decompress(comp_msg)
  56.     decomp_msg_len = len(decomp_msg)*8
  57.     print 'Decompressing Message into {x} Bits.'.format(x=decomp_msg_len)
  58.     print 'Decompressed Message:{}'.format(decomp_msg)
  59.     assert(msg==decomp_msg)
  60.     print 'Message Matches!'
Add Comment
Please, Sign In to add comment