题目来源:【廖雪峰的官方网站-map/reduce】
利用map
和reduce
编写一个str2float
函数,把字符串'123.456'
转换成浮点数123.456
:
from functools import reduceCHAR_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 = 0def to_float(f, n):nonlocal pointif n == -1:point = 1return fif point == 0:return f * 10 + nelse:point = point * 10return f + n / pointreturn 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('测试失败!')
代码参考:/michaelliao/learn-python3/blob/master/samples/functional/do_reduce.py