码迷,mamicode.com
首页 > 其他好文 > 详细

map/reduce

时间:2018-04-28 19:35:23      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:turn   coding   too   lower   dig   转换   pow   har   nbsp   

1、

利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam‘, ‘LISA‘, ‘barT‘],输出:[‘Adam‘, ‘Lisa‘, ‘Bart‘]:

# -*- coding: utf-8 -*-

def normalize(name):
    return name.lower().capitalize()

# 测试:
L1 = [‘adam‘, ‘LISA‘, ‘barT‘]
L2 = list(map(normalize, L1))
print(L2)

 

2、

Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:

# -*- coding: utf-8 -*-
from functools import reduce

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

print(‘3 * 5 * 7 * 9 =‘, prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print(‘测试成功!‘)
else:
    print(‘测试失败!‘)

 

3、

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

# -*- coding: utf-8 -*-
from functools import reduce

def str2float(s):

    DIGITS = {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}
    s=s.split(‘.‘,1)
    s1 = s[0]  # 取整数部分
    s2 = s[1]  # 取小数部分

    def char2num(n):
        return DIGITS[n]
    m1=reduce(lambda x,y:x*10+y,map(char2num,s1))
    m2=reduce(lambda x,y:x*10+y,map(char2num,s2))
    m3=pow(10,-len(s2)) # 举例pow(10,-3)代表10的-3次方,即0.001
    
    return m1 + m2*m3
print(‘str2float(\‘123.456\‘) =‘, str2float(‘123.456‘))
if abs(str2float(‘123.456‘) - 123.456) < 0.00001:
    print(‘测试成功!‘)
else:
    print(‘测试失败!‘)

  

map/reduce

标签:turn   coding   too   lower   dig   转换   pow   har   nbsp   

原文地址:https://www.cnblogs.com/zuxing/p/8969054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!