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

版权声明:本文为博主原创文章,欢迎大家转载,但是要注明我的文章地址。 https://blog.csdn.net/program_developer/article/details/86572110
微信公众号

题目来源:【廖雪峰的官方网站-map/reduce】

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

from functools import reduce

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

def str2float(s):
    nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
    point = 0
    def to_float(f, n):
        nonlocal point
        if n == -1:
            point = 1
            return f
        if point == 0:
            return f * 10 + n
        else:
            point = point * 10
            return f + n / point
    return reduce(to_float, nums, 0.0)

print('str2float(\'123.456\') =', str2float('123.456'))

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

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

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/86572110