Is there a good python library that can turn numbers into their respective “symbols”? [closed]

只谈情不闲聊 提交于 2019-12-02 08:27:38

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.

>>> int("a", 36)
10
>>> int("z", 36)
35
>>> int("10", 36)
36

The other direction is more complicated, but try this ActiveState recipe.

Normally base conversions make no distinction between cases. I'm not sure how to completely extend this to make that distinction, but the recipe should give you a start.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!