Discuss / Python / 第三题

第三题

Topic source

Resalee

#1 Created at ... [Delete] [Delete and Lock User]

没有对是否有小数点做判断

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):
    #字符转数字
    def char2num(s):
        return DIGITS[s]
    #list转数字
    def fn(x, y):
        return x*10 + y

    #小数点位置
    p = s.find('.')
    #去除小数点的字符串
    newstr = s[:p] + s[(p+1):]
    #小数位
    f = len(s[(p+1):])
    return reduce(fn, map(char2num, newstr))/(10**f)
    

  • 1

Reply