第三题:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
DIGITS = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
def char2num(s):
return DIGITS[s]
return reduce(lambda x,y: x*10+y, map(char2num, s.replace('.','')))/(10**(len(s)-s.find('.')-1))
Sign in to make a reply
landingguymmm
第三题:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
DIGITS = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
def char2num(s):
return DIGITS[s]
return reduce(lambda x,y: x*10+y, map(char2num, s.replace('.','')))/(10**(len(s)-s.find('.')-1))