[ Python

1. 利用mapreduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456

from functools import reduce
def str2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

def str2float(s):
    if '.' in s:
        # 将字符串s拆分成list类型
        s = s.split('.')
        # 通过小数点分割,分别计算然后相加
        return reduce(lambda x, y: x*10+y, map(str2num,s[0])) + reduce(lambda x, y: x/10+y, map(str2num, s[1][::-1]))/10
    else:
        return  reduce(lambda x, y: x*10+y, map(str2num, s))
s1 = str2float('123.456')
print(s1)
View Code

2. 编写一个函数,可以接受一个list并利用reduce()求积:

def prod(L):
    def num(x, y):
        return x*y
    return reduce(num, L)

L = [1,2,3,4]
print(prod(L))
View Code
原文地址:https://www.cnblogs.com/hukey/p/7142531.html