Discuss / Python / 最后一题 str2float

最后一题 str2float

Topic source

_Dvel

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

交作业,这个应该是简单易懂吧

from functools import reduce


def str2float(s):
    if s == '0':
        return 0
    # 用户输入'.123'这样以'.'开头的字符串时,在前面加个'0'。
    if s[0] == '.':
        s = '0' + s

    l = s.split('.')  # 得到 ['123', '456']

    # 整数部分
    num1 = reduce(lambda x, y: x * 10 + y, map(int, l[0]))  # 得到int类型的123

    # 小数部分
    num2 = reduce(lambda x, y: x * 10 + y, map(int, l[1]))  # 得到int类型的456
    for i in range(len(l[1])):
        num2 = num2 / 10  # 循环完成后,最终得到float类型的0.456

    return num1 + num2


r = str2float('123.456')
print(r)  # 123.456
print(isinstance(r, float))  # True

  • 1

Reply