在python中定义一个新的数值基(新字符集) [英] Define a new numerical base in python (new charset)

查看:105
本文介绍了在python中定义一个新的数值基(新字符集)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Python中定义一个新的数值基.

I would like to know how to define a new numerical base in Python.

例如:

base dimension = 4
Charset = 'u', '$', '6', '}' (from the least important to the most)

我想知道如何创建和处理它,以便能够进行简单的算术运算,例如:

I would like to know how to create and handle it, to be able to do simple arithmetic like:

$} + 6u * 6 = $$}
 7 +  8 * 2 =  23

我知道我可以使用replace替换u -> 0$ -> 1等,并使用int()函数.但是int()没有为base > 36定义,我将不得不处理这些情况.

I know I could use replace to replace u -> 0, $ -> 1 and so on, and use the int() function. However int() is not defined for base > 36, and I will have to handle these cases.

我知道我可以做自己的函数将它们转换为base 10,进行数学运算,然后将它们转换回,但是如果可能的话,我想避免这种情况.

I know I could make my own function to convert them to base 10, do the math, and convert them back, but I would like to avoid that if possible.

推荐答案

def str_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]



def charset(chars):
    class cls(int):
        __slots__ = ()

        def __new__(cls, src):
            if isinstance(src, str):
                return int.__new__(
                    cls,
                    ''.join(str(chars.index(i)) for i in src),
                    len(chars)
                )
            return int.__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

用法:

test = charset('u$6}')
print(test( test('$}') + test('6u') * test('6') ) ) # => '$$}'

查看其在线运行情况: http://rextester.com/WYSE48066

See it working online: http://rextester.com/WYSE48066

此刻,我太累了,无法解释.

At the moment, I'm too tired to explain it.

这篇关于在python中定义一个新的数值基(新字符集)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆