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(‘测试失败!‘)
原文:https://www.cnblogs.com/zuxing/p/8969054.html