廖雪峰老师的教程里面的一道题把字符串转成浮点型
利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456:
def str2float(s):
DISGITS = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
s1 = s.split('.')[0]
s2 = s.split('.')[1]
s2 = s2[::-1]
def str2num(s):
return int(s)
def fn1(x, y):
return x * 10 + y
def fn2(x, y):
return x * 0.1 +y
def sumup(x, y):
return x + y
return sumup(reduce(fn1, map(str2num, s1)), 0.1*reduce(fn2, map(str2num, s2)))
if __name__=="__main__":
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('success!')
else:
print('error!')