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

那年仲夏 提交于 2019-12-02 16:43:14

问题


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?


回答1:


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.




回答2:


>>> 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.



来源:https://stackoverflow.com/questions/4351467/is-there-a-good-python-library-that-can-turn-numbers-into-their-respective-symb

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