Created
September 3, 2013 14:03
-
-
Save ltiao/6424377 to your computer and use it in GitHub Desktop.
Quick 10 minute implementation of (static) arithmetic coding.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| import random | |
| prob = { | |
| 'a': (0, 0.4), | |
| 'b': (0.4, 0.3), | |
| 'c': (0.7, 0.2), | |
| '@': (0.9, 0.1) | |
| } | |
| def encode(string, prob): | |
| start = 0 | |
| width = 1 | |
| for ch in string: | |
| d_start, d_width = prob[ch] | |
| start += d_start*width | |
| width *= d_width | |
| return random.uniform(start, start+width) | |
| def decode(num, prob): | |
| string = [] | |
| while True: | |
| for symbol, (start, width) in prob.iteritems(): | |
| if 0 <= num - start < width: | |
| num = (num - start) / width | |
| string.append(symbol) | |
| break | |
| if symbol == '@': | |
| break | |
| return ''.join(string) | |
| encoded_number = encode('aababcbcacb@', prob) | |
| decoded_string = decode(encoded_number, prob) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this have a problem
"encoded_number = encode('bbacaaaaaaaabcbcaaabacbacbccccaaaabccaa@', prob)"