Discuss / Python / 第三题

第三题

Topic source

劳逸结合

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reduce

def str2float(s):
    L1,L2='',''    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]
    def fn(x,y):
        return x*10+y
    n=s.index('.')
    L1=s[:n]
    L2=s[n+1:]
    a=reduce(fn, map(char2num, L1))
    b=reduce(fn, map(char2num, L2))
    c=b/10**len(L2)
    return a+c

print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

  • 1

Reply