内容来自廖雪峰的官方网站。
1、Python提供的sum()
函数可以接受一个list并求和,请编写一个prod()
函数,可以接受一个list并利用reduce()
求积。
from functools import reduce def prod(L): def f(x, y): return x * y; return reduce(f , L)
2、利用map
和reduce
编写一个str2float
函数,把字符串'123.456'
转换成浮点数123.456。
不会用map reduce。。。
from functools import reduce def str2float(s): c = 0; pw = 1; for x in s: if x != '.': c = c * 10 + int(x) posi = s.find('.', 0) for i in range(len(s) - posi - 1): pw *= 0.1 return c * pw