是否有一个好的python库可以将数字转换为各自的“符号”? [英] Is there a good python library that can turn numbers into their respective "symbols"?
本文介绍了是否有一个好的python库可以将数字转换为各自的“符号”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
0 = 0
1 = 1
...
9 = 9
10 = a
11 = b
...
35 = z
36 = A
37 = B
...
60 = Z
61 = 10
62 = 11
...
70 = 19
71 = 1a
72 = 1b
我不知道这叫什么。什么基础?
我想要的是一个可以将数字转换成这些数字的函数,然后将它们转换回数字。
是否有一个简单的功能可以做到这一点?
解决方案
你可以继承number.Number:
'pre>
DEF BASEN(碱,字母表= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):
类_baseN(numbers.Number):
位数=字母表[:base]
def __init __(self,value):
if isinstance(value,int):
self.value = value
if self.value == 0:
self.string ='0'
else:
tmp = [abs(value)]
而tmp [0]!= 0:
tmp [:1] = divmod(tmp [0],base)
tmp = [tmp中我的字母[i]]
tmp [0] =' - '如果self.value< 0 else''
self.s tring =''。join(tmp)
elif isinstance(value,str):
assert(value.isalnum())
self.string = str(value)
self .value = 0
表示d值:
self.value = self.value * base + self.digits.index(d)
else:
self.value = 0
self.string ='0'
def __int __(self):
return self.value
def __str __(self):
return self.string
def __repr __(self):
return self.string
def __add __(self,another):
return self .__ class __(self.value + int(another))
return如果基数> len(字母)其他_baseN
发现另一个错误。将其更改为工厂功能。现在可以处理一般情况。
0 = 0
1 = 1
...
9 = 9
10 = a
11 = b
...
35 = z
36 = A
37 = B
...
60 = Z
61 = 10
62 = 11
...
70 = 19
71 = 1a
72 = 1b
I don't know what this is called. Base something?
All I want is a function that can convert the numbers into these, and these back to numbers.
Is there an easy function that can do this?
解决方案
You may inherit numbers.Number:
def baseN(base,alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):
class _baseN(numbers.Number):
digits=alphabet[:base]
def __init__(self,value):
if isinstance(value,int):
self.value=value
if self.value==0:
self.string='0'
else:
tmp=[abs(value)]
while tmp[0]!=0:
tmp[:1]=divmod(tmp[0],base)
tmp=[alphabet[i] for i in tmp]
tmp[0]='-' if self.value<0 else ''
self.string=''.join(tmp)
elif isinstance(value,str):
assert(value.isalnum())
self.string=str(value)
self.value=0
for d in value:
self.value=self.value*base+self.digits.index(d)
else:
self.value=0
self.string='0'
def __int__(self):
return self.value
def __str__(self):
return self.string
def __repr__(self):
return self.string
def __add__(self,another):
return self.__class__(self.value+int(another))
return None if base>len(alphabet) else _baseN
Found another bug. Change it to a factory function. Now may handle general situation.
这篇关于是否有一个好的python库可以将数字转换为各自的“符号”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文