利用map和reduce编写一个strtofloat函数,把字符串'123.456'转换成浮点数123.456,如下:
from functools import reduce
digits={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def strtofloat(s):
s=s.split('.')
def f(x,y):
return x*10+y
def g(x,y):
return x/10+y
def chartunum(s):
return digits[s]
return reduce(f,list(map(chartunum,s[0])))+1/10*reduce(g,list(map(chartunum,s[1]))[::-1])
s='123.456'
print(strtofloat(s))
结果为123.456