Define A New Numerical Base In Python (new Charset)
I would like to know how to define a new numerical base in Python. For example: base dimension = 4 Charset = 'u', '$', '6', '}' (from the least important to the most) I would like
Solution 1:
Rather than replace
, you can use dictionaries to translate back and forth between the charset and regular ints, something like:
charset = 'u$6}'
b = len(charset) #base
vals = {c:i for i,c inenumerate(charset)}
digits = {vals[c]: c for c in vals} #inverse dictionarydeftoInt(s):
returnsum(vals[c]*b**i for i,c inenumerate(reversed(s)))
deftoNewBase(n):
nums = [] if n > 0else [0]
while n > 0:
n,r = divmod(n,b)
nums.append(r)
return''.join(digits[i] for i inreversed(nums))
defadd(s,t):
return toNewBase(toInt(s) + toInt(t))
defsubtract(s,t):
return toNewBase(toInt(s) - toInt(t))
defmultiply(s,t):
return toNewBase(toInt(s) * toInt(t))
defdivide(s,t):
return toNewBase(toInt(s) // toInt(t))
typical output:
>>> add('$}',multiply('6u','6'))
'$$}'
Solution 2:
defstr_base(number, base):
# http://stackoverflow.com/a/24763277/3821804
(d,m) = divmod(number,len(base))
if d > 0:
return str_base(d,base)+base[m]
return base[m]
defcharset(chars):
classcls(int):
__slots__ = ()
def__new__(cls, src):
ifisinstance(src, str):
returnint.__new__(
cls,
''.join(str(chars.index(i)) for i in src),
len(chars)
)
returnint.__new__(cls, src)
def__str__(self):
return str_base(self, chars)
def__repr__(self):
return'%s(%r)' % (type(self).__name__, str(self))
cls.__name__ = 'charset(%r)' % chars
return cls
Usage:
test = charset('u$6}')
print(test( test('$}') + test('6u') * test('6') ) ) # => '$$}'
See it working online: http://rextester.com/WYSE48066
At the moment, I'm too tired to explain it.
Post a Comment for "Define A New Numerical Base In Python (new Charset)"