Discuss / Python / 打卡—第三题

打卡—第三题

Topic source
def str2float(s):

    # 'int' -> int
    digits = {'1' : 1, '2' : 2, '3' : 3, '4' :
4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '0' : 0}
    def char2num(c):
        return digits[c]
    def list2num(x, y):
        return x * 10 + y

    # L储存无小数点版本的str转化为一个个int的list 
    # 并以此计算出组合后int:num_no_dot
    L = list(map(char2num, s.replace('.','')))
    num_no_dot = reduce(list2num, L)

    # 判断str中是否有小数点,若有小数点,根据小数点后的位数将num_no_dot处理为相应的float
    if s.find('.') == -1:
        return num_no_dot
    else:
        num_dot = num_no_dot / pow(10, len(s) - s.find('.') - 1)
    return num_dot

  • 1

Reply