DIGITS = {‘0’: 0, ‘1’: 1, ‘2’: 2, ‘3’: 3, ‘4’: 4, ‘5’: 5, ‘6’: 6, ‘7’: 7, ‘8’: 8, ‘9’: 9,’.’:’.’}
from functools import reduce
def f1(x,y):
return x*10+y
def f2(x,y):
return x*0.1+y
def fn(s):
return DIGITS[s]
def str2float(s):
t=list(map(fn,s))
for n in range(len(t)):
if t[n]==’.’:
s1=t[0:n]
#print(s1)
s2=t[n+1:len(t)]
s3=s2[::-1]
#print(s3)
break
else:
n=n+1
r1=reduce(f1,s1)
#print(r1)
r2=reduce(f2,s3)*0.1
#print(r2)
r=r1+r2
return rstr2float(‘123.456’)
123.456
answer 2:
CHAR_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 = 0
def to_float(f, n):
nonlocal point
if n == -1: *碰到小数点,值不变
point = 1
return f *
if point == 0: *小数点左边
return f * 10 + n *
else: *小数点右边
point = point * 10
return f + n / point *
return reduce(to_float, nums, 0.0)