Discuss / Python / str2float

str2float

Topic source

Kylin_Gu

#1 Created at ... [Delete] [Delete and Lock User]
def str2float(s):
    def offset(s):
        return power(0.1, len(s) -1 - s.index('.'))
    def char2nums(s):
        DIGISTS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
        return DIGISTS[s]
    def fn(x, y):
        if y == '.': return x
        return x * 10 + y
    return reduce(fn, map(char2nums, s)) * offset(s)

思路其实与'12345'转换成12345是一样的,不过只是要把结果乘上'.'所确定的小数位。

2015质变

#2 Created at ... [Delete] [Delete and Lock User]

你这个思路是对的,比较简洁,我的思路 冗余了: def mult(x,y): return 10x+y; def pointMul(x,y): return 0.1x+y; def digest(s): dic = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.':-1} return dic[s];

def str2float(s): L = list(map(digest,s)); idx = L.index(-1); M1 = L[0:idx]; M2 =L[idx+1:]; res = reduce(mult,M1) + 0.1*reduce(pointMul,reversed(M2)); return res;

_WangZ--

#3 Created at ... [Delete] [Delete and Lock User]

为毛我 pow(0.1, len(s) -1 - s.index('.')) 会打印:

0.0010000000000000002


  • 1

Reply