欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python各种进制求值的方法(代码实例)

程序员文章站 2022-07-02 19:03:59
python各种进制求值的方法(代码实例) def checkio(str_number, radix): str_int = dict(map(lambda x,...
python各种进制求值的方法(代码实例)
def checkio(str_number, radix):
    str_int = dict(map(lambda x,y:(y, x), [ i for i in range(10, 36) ], [ chr(i)  for i in range(97, 123) ]))
    int_int = dict(map(lambda x,y:(str(x),y), [ i for i in  range(10) ], [ i for i in range(10) ]))
    sum = 0
    times = 0
    for i in reversed(str_number):
        v = int_int.get(i, None)
        if v == None:
            v = str_int.get(i.lower(), None)
        if v >= radix:
            return -1
        else:
            sum += v if times == 0 else v*radix**times
        times += 1
    return sum
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio("AF", 16) == 175, "Hex"
    assert checkio("101", 2) == 5, "Bin"
    assert checkio("101", 5) == 26, "5 base"
    assert checkio("Z", 36) == 35, "Z base"
    assert checkio("AB", 10) == -1, "B > A = 10"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")