Python map/reduce练习(一)

利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456:

from functools import reduce

def str2float(s):
    def str2num(s):
        DIGITS = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9};
        return DIGITS[s];
    def num2int(L):
        return reduce(lambda x, y: x * 10 + y,L)
    def num2float(L):
        L.reverse()
        b=[0]
        L.extend(b)
        return reduce(lambda x, y: x / 10 + y,L)
    s1 = s.split('.')[0];
    s2 = s.split('.')[1];
    s3 =(list)(map(str2num,list(s2)))
    ##round(float,num)四舍五入到小数点第几位数字
    return num2int(map(str2num,list(s1)))+round(num2float(s3),3)

print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

这个代码感觉还是不能满足所有浮点数,只解决本题

猜你喜欢

转载自blog.csdn.net/weixin_37893376/article/details/84672534