代码如下:
# -*- coding: utf-8 -*- from functools import reduceDIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}def str2float(s): def char2num(s): return DIGITS[s] def fn(x, y): return x * 10 + y integer_str = s.split('.')[0] decimal_str = s.split('.')[1] integer_num = map(char2num, integer_str) decimal_num = map(char2num, decimal_str) # <class 'map'> float_num = reduce(fn, integer_num) + reduce(fn, decimal_num) / pow(10, len(decimal_str)) return float_numprint('str2float(\'123.456\') =', str2float('123.456'))if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!')else: print('测试失败!')
Sign in to make a reply
lldhsds
代码如下: