在python中定义一个新的数字基(new charset)

时间:2015-10-20 15:14:33

标签: python base

我想知道如何在Python中定义一个新的数字基础。

例如:

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  e.returnValue = confirmationMessage;     // Gecko and Trident
  return confirmationMessage;              // Gecko and WebKit
});

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

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

我知道我可以使用$} + 6u * 6 = $$} 7 + 8 * 2 = 23 替换replaceu -> 0等等,并使用$ -> 1函数。但是int()未定义int(),我将不得不处理这些情况。

我知道我可以创建自己的函数将它们转换为base > 36,进行数学运算并将其转换回来,但如果可能的话我想避免这种情况。

2 个答案:

答案 0 :(得分:1)

而不是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'))
'$$}'

典型输出:

{{1}}

答案 1 :(得分:1)

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

目前,我太累了,无法解释。