【python】利用map和reduce编写一个str2float函数,把字符串‘123.456‘转换成浮点数123.456(廖雪峰)

练习

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

# -*- coding: utf-8 -*-
from functools import reduce

def str2float(s):
    def f(x, y):
        return x * 10 + y
    def char2num(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]
    n = s.index('.')
    return reduce(f, map(char2num, [x for x in s[: n]])) + reduce(f, map(char2num, [x for x in s[n + 1 :]])) / 10 ** (len(s)-n-1)

 

你可能感兴趣的:(python)