Skip to content

Instantly share code, notes, and snippets.

@cocomoff
Created June 19, 2019 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocomoff/5c60345f0929266bf8c7984af032dc04 to your computer and use it in GitHub Desktop.
Save cocomoff/5c60345f0929266bf8c7984af032dc04 to your computer and use it in GitHub Desktop.
高速文字列解析の世界 §2.5 符号
# -*- coding: utf-8 -*-
def unary(x):
return "0" * (x - 1) + "1"
def binary(x):
return bin(x)[2:]
def gamma(x):
bx = binary(x)
c1 = unary(len(bx))
return c1 + bx[1:]
def delta(x):
bx = binary(x)
c1 = gamma(len(bx))
return c1 + bx[1:]
def golomb(x, k=8):
xp = x - 1
r = (xp // k) + 1
m = xp % k
c1 = unary(r)
c2 = binary(m)
while len(c2) < len(binary(k - 1)):
c2 = '0' + c2
return c1 + c2
if __name__ == '__main__':
lX = [1, 3, 5, 10, 100]
for x in lX:
unary_x = unary(x)
binary_x = binary(x)
print("x={}".format(x))
# print("(x)₁={}".format(unary_x))
print("(x)₂={}".format(binary_x))
gamma_x = gamma(x)
delta_x = delta(x)
golomb_x = golomb(x)
print("γ(x)={}".format(gamma_x))
print("δ(x)={}".format(delta_x))
print("G(x)={}".format(golomb_x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment