Discuss / Python / 第三题: 先转换成int, 在根据小数点的位置做调整,感觉有点笨重

第三题: 先转换成int, 在根据小数点的位置做调整,感觉有点笨重

Topic source

# 先转换成int, 在根据小数点的位置做调整

from functools import reduce

digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2float(s):

    if '.' in s:

        index = s.index('.')

        n = len(s)-index

        s = s.replace('.', '')

    else:

        n = 1

    def cha2num(s):

        return digits[s]

    def fun(x, y):

        return x*10+y

    return reduce(fun, map(cha2num, s))/10**(n-1)


  • 1

Reply