当前位置: 移动技术网 > IT编程>脚本编程>Python > python各种进制求值的方法(代码实例)

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

2017年12月22日  | 移动技术网IT编程  | 我要评论

恒宇双星多少钱,男人们别争宠,12999语文网

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!")

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网