Discuss / Python / 第三个答案

第三个答案

Topic source

lemon9527

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

from functools import reduce

def str2float(s):

# 移除小数点,把小数变为整数,记录下小数点的位置
n = 0
for x in s:
    n = n+1
    if x=='.':
        s = s.replace('.', '')
        break

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def fn(x,y):
    return x*10 + y

def char2num(s):
    return DIGITS[s]

#移除小数点后的整数
print(reduce(fn, map(char2num, s)))

#加回小数点, 乘以 10**(len(s)-n+1)
print(reduce(fn, map(char2num, s))/(10**(len(s)-n+1)))

str2float('21.65')


  • 1

Reply