Discuss / Python / Hw
# -*- coding: utf-8 -*-

from functools import reduce

def str2float(s):
    a, b = s.split(".")
    num = reduce(lambda x, y: x * 10 + y, map(char2num, a + b))
    return num/(10**len(b))

def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]


print('str2float(\'123.000\') =', str2float('123.000'))
print('str2float(\'123.456\') =', str2float('123.456'))



#str2float('123.000') = 123.0
#str2float('123.456') = 123.456

len(b) works because b is a string:

a, b = s.split(".")

In the case of '123.000', b = '000', len(b) = 3.


  • 1

Reply