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

题目来源:廖雪峰个人网站Python3教程(https://www.liaoxuefeng.com/)

代码思路参考:https://github.com/michaelliao/learn-python3/blob/master/samples/functional/do_reduce.py

Python2实现代码如下:

#encoding=utf-8
flag=0
def str2float(s):
    global flag
    flag=0 #每次调用函数,就将flag恢复到初始值
    CH_TO_NUM={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'.':-1}
    nums=map(lambda ch:CH_TO_NUM[ch],s)
    def f1(x,y):
        global flag
        if y==-1:
            flag=1
            return x #小数点前的整数部分
        if flag==0:
            return x*10+y
        else:
            flag=flag*0.1
            return x+y*flag
    def f2(x,y):
        return x*0.1+y
    if nums[0]==-1:#特殊情况(.12345),单独处理
        return 0.1*reduce(f2,nums[1:][::-1]) #取小数部分并倒序
    else :
        return reduce(f1,nums)
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')  
print(str2float('0'))
print(str2float('123.456'))
print(str2float('123.45600'))
print(str2float('0.1234'))
print(str2float('.1234'))
print(str2float('120.0034'))

猜你喜欢

转载自blog.csdn.net/wustjk124/article/details/80707578