Skip to content

Instantly share code, notes, and snippets.

@ltiao
Created September 3, 2013 14:03
Show Gist options
  • Select an option

  • Save ltiao/6424377 to your computer and use it in GitHub Desktop.

Select an option

Save ltiao/6424377 to your computer and use it in GitHub Desktop.
Quick 10 minute implementation of (static) arithmetic coding.
#!/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)
@karimpazoki

Copy link
Copy Markdown

I think this have a problem
"encoded_number = encode('bbacaaaaaaaabcbcaaabacbacbccccaaaabccaa@', prob)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment