#第一题 # -*- coding: utf-8 -*- def normalize(name): x=name[0].upper()+name[1:].lower() return x # 测试: L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2)
#第二题 # -*- coding: utf-8 -*- 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('测试失败!')
#第三题 # -*- coding: utf-8 -*- from functools import reduce #法一:使用split()函数 def str2float(s): def char2num(x): Digits={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return Digits[x] x1=s.split('.')[0] x2=s.split('.')[1] a1=reduce(lambda x,y:10*x+y, map(char2num, x1)) a2=reduce(lambda x,y:0.1*x+y, map(char2num, x2[::-1])) return a1+0.1*a2 #法二:使用replace函数 def str2float(s): def char2num(x): Digits={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return Digits[x] for i in range(len(s)): if s[::-1][i]=='.': spot=i a=s.replace('.','') return reduce(lambda x,y:10*x+y, map(char2num, a))/10**spot print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!')
Sign in to make a reply
状元刚01