Advertisement
here2share

# t_zbase_n_demo4all.py

Jan 21st, 2021
1,019
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. # t_zbase_n_demo4all.py
  2.  
  3. def zbase(n, b=3,length=3):
  4.     t = b**(length)
  5.     if n < t:
  6.         n=n+t
  7.         if n == 0:
  8.             return [0]
  9.         values = []
  10.         for z in 'Z'*length:
  11.             r = n % b
  12.             n /= b
  13.             values.append(r)
  14.         return values[::-1]
  15. 0
  16.  
  17. ttt = 'abcdefghijklmnopqrstuvwxyz'[:4]
  18.  
  19. def base2index(base, target, length):
  20.     result = 0
  21.     baseLen = len(base)
  22.     for i, value in enumerate(target):
  23.         result += base.index(value) * baseLen**(length - 1 - i)
  24.     return result
  25.  
  26. def index2base(base, target, length):
  27.     result = zbase(target, len(base), length)
  28.     if result:
  29.         return ''.join([base[i] for i in result])
  30.  
  31. i = 0
  32. while 1:
  33.     t = index2base(ttt, i, 4)
  34.     if not t:
  35.         break
  36.     print 'from '+str(i).zfill(3), 'to', [t], 'converted back to', base2index(ttt, t, 4)
  37.     print  
  38.     i += 1
  39. 0
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement