我想知道如何在 Python 中定义新的数字基数。
例如:
base dimension = 4
Charset = 'u', '$', '6', '}' (from the least important to the most)
我想知道如何创建和处理它,以便能够进行简单的算术,例如:
$} + 6u * 6 = $$}
7 + 8 * 2 = 23
我知道我可以使用 replace
来替换 u -> 0
、$ -> 1
等,并使用 >int()
函数。但是 int()
没有为 base > 36
定义,我将不得不处理这些情况。
我知道我可以创建自己的函数将它们转换为base 10
,进行数学计算,然后将它们转换回来,但如果可能的话,我想避免这种情况。
最佳答案
您可以使用字典在字符集和常规整数之间来回转换,而不是替换
,例如:
charset = 'u$6}'
b = len(charset) #base
vals = {c:i for i,c in enumerate(charset)}
digits = {vals[c]: c for c in vals} #inverse dictionary
def toInt(s):
return sum(vals[c]*b**i for i,c in enumerate(reversed(s)))
def toNewBase(n):
nums = [] if n > 0 else [0]
while n > 0:
n,r = divmod(n,b)
nums.append(r)
return ''.join(digits[i] for i in reversed(nums))
def add(s,t):
return toNewBase(toInt(s) + toInt(t))
def subtract(s,t):
return toNewBase(toInt(s) - toInt(t))
def multiply(s,t):
return toNewBase(toInt(s) * toInt(t))
def divide(s,t):
return toNewBase(toInt(s) // toInt(t))
典型输出:
>>> add('$}',multiply('6u','6'))
'$$}'
关于python - 在python中定义一个新的数字基数(新的字符集),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33240388/