题目1:
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
解答:
def normalize(name):
return list(map(lambda s: s[0].upper() + s[1:].lower(),name))
print(normalize(name))
# 测试:
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):
return reduce(lambda x, y: x * y, L)
题目3:
利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
解答:
from functools import reduce
DIGITS={'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7urn ':7, '8':8, '9':9}
def str2float(s):
s1 = s.split('.')
def char2nums(s):
return DIGITS[s]
def f(x,y):
return x*10 + y
def StrToInt(s):
return reduce(f, map(char2nums,s))
s2 = list(map(StrToInt, s1))
return s2[0]+ s2[1]/pow(10, len(s1[1]))
print('str2float(\'123.456\')=', str2float('123.456'))
if abs(str2float('123.456')-123.456)<0.00001:
print('测试成功!')
else:
print('测试失败!')