Discuss / Python / 第三题

第三题

Topic source

pipi-hongwy

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

def str2float(s):

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

    def char2num(s):

        return DIGITS[s]

    def fn(x, y):

        return x * 10 + y

    point=s.index('.')   #小数点的位置

    L=list(s)                #字符串转list

    L1=L[:point]         #小数点前半段list

    L2=L[point+1:]     #小数点后半段list

    return reduce(fn,map(char2num,L1))+reduce(fn,map(char2num,L2))*pow(10,-point)  #前段+后端*0.001=结果

昨已将

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

最后一行的pow(10,-point)有问题,这道题凑巧整数、小数部分是一样的长度 所以答案是对的 我把它换成了pow(10,-len(L2))

L=list(s)这步其实可以不用

这样L1,L2仍然是str,但是map的时候str也可以当作list,结果还是一样的


  • 1

Reply