利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:

时间:2022-04-11 01:25:50
 #!/usr/bin/env python3
# -*- coding: utf-8 -*- from functools import reduce CHAR_TO_INT = {
'': 0,
'': 1,
'': 2,
'': 3,
'': 4,
'': 5,
'': 6,
'': 7,
'': 8,
'': 9
} def str2int(s):
ints = map(lambda ch: CHAR_TO_INT[ch], s)
return reduce(lambda x, y: x * 10 + y, ints) print(str2int(''))
print(str2int(''))
print(str2int('')) CHAR_TO_FLOAT = {
'': 0,
'': 1,
'': 2,
'': 3,
'': 4,
'': 5,
'': 6,
'': 7,
'': 8,
'': 9,
'.': -1
} def str2float(s):
nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
point = 0
def to_float(f, n):
nonlocal point
if n == -1:
point = 1
return f
if point == 0:
return f * 10 + n
else:
point = point * 10
return f + n / point
return reduce(to_float, nums, 0.0) print(str2float(''))
print(str2float('123.456'))
print(str2float('123.45600'))
print(str2float('0.1234'))
print(str2float('.1234'))
print(str2float('120.0034'))