# -*- coding: utf-8 -*-
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 str2float(s):
n=s.index('.') #找出.的位置
t=len(s)
p=t-n-1 #结果需要乘10的-p次幂
s=s.replace('.','') #去掉字符串中的. 用空字符串替换
def char2num(x):
return digits[x]
sf=reduce(lambda x,y:x*10+y,map(char2num,s))
return sf*pow(10,-p)
print('str2float(\'123.456\') =', str2float('123.456'))
#if abs(str2float('123.456') - 123.456) < 0.00001:
if abs(str2float('123.456') - 123.456) == 0:
print('测试成功!')
else:
print('测试失败!')
Sign in to make a reply
nstart0902
# -*- coding: utf-8 -*-
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 str2float(s):
n=s.index('.') #找出.的位置
t=len(s)
p=t-n-1 #结果需要乘10的-p次幂
s=s.replace('.','') #去掉字符串中的. 用空字符串替换
def char2num(x):
return digits[x]
sf=reduce(lambda x,y:x*10+y,map(char2num,s))
return sf*pow(10,-p)
print('str2float(\'123.456\') =', str2float('123.456'))
#if abs(str2float('123.456') - 123.456) < 0.00001:
if abs(str2float('123.456') - 123.456) == 0:
print('测试成功!')
else:
print('测试失败!')