1.
def normalize(name):
f = str.upper(name[0]) + str.lower(name[1:])
return f
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
2.
from functools import reduce
def prod(L):
return reduce(lambda x, y: x * y, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
3.
from functools import reduce
def str2float(s):
def char2num(s1):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
return digits[s1]
number = list(map(char2num, s))
plot = number.index('.')
intpart = reduce(lambda x, y: x * 10 + y, number[:plot])
number.reverse()
plot = number.index('.')
floatpart = reduce(lambda x, y: x * 0.1 + y, number[:plot])
return intpart + 0.1 * floatpart
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')