Discuss / Python / 请教:这条代码为什么能输出0.1?

请教:这条代码为什么能输出0.1?

Topic source

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from functools import reduce


CHAR_TO_FLOAT = {
    '0': 0,
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 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('.1'))

我怎么手算出来值是-90

这里计算得到的nums应该是含有-1,1两个值的,但是后续带入to_float第一次运算得到-9,然后-9和0.0带入to_float运算得到-90,求大神指点

return reduce(to_float, nums,0.0)

这里为什么输入了nums,0.0 两个参数,这该怎么传递进to_float函数呢

return reduce(to_float, nums, 0.0)

貌似通过经验方法知道是什么意思了,这个0.0和nums一起出现,然后会重新组成一个新的List,[0.0,1,2,3,4,5,6,7,8,9,-1],即他会跑到nums元素的前面,然后再按照.

return reduce(to_float,[0.0,1,2,3,4,5,6,7,8,9,-1])

来计算。

类似的例子可用下面这个来验证:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from functools import reduce

def fn(x, y):
    return x * 10 + y
print(reduce(fn, [1, 3, 5, 7, 9],9))

输出913579,即后面的那个9会跑到最前面来参与计算

作业1:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def normalize(name):
    return name.capitalize()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

作业2:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from functools import reduce
def Multiply(x, y):
    return x * y
def prod(L):
    return reduce(Multiply,L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))

作业3参考廖老师的

诚氏阿黄

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

貌似通过经验方法知道是什么意思了,这个0.0和nums一起出现,然后会重新组成一个新的List,[0.0,1,2,3,4,5,6,7,8,9,-1],即他会跑到nums元素的前面,然后再按照.

想问,为什么会跑到nums元素前面?


  • 1

Reply