#利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
def normalize(name): return name.capitalize()
L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2)
#请编写一个prod()函数,可以接受一个list并利用reduce()求积:
from functools import reduce
def prod(L): def pow1(x,y): return x*y return reduce(pow1,L)
print('3 5 7 * 9 =', prod([3, 5, 7, 9])) if prod([3, 5, 7, 9]) == 945: print('测试成功!') else: print('测试失败!')
#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
def str2float(s):
def f1(x): dic1={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} if x=='.': pass else: return dic1[x] def f2(x,y): return x*10+y n=1 #初始化 n1=0#初始化 s1=''#初始化 for i in s: #得到小数点的位置以及去除掉小数点后的字符串s1 if i!='.': n=n+1 s1=s1+i else: n1=n a=len(s)-n1#小数点后面的位数 b=reduce(f2,map(f1,s1))#得到整数 c=b/(pow(10,a))#得到浮点数 return c
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
bai渡者
#利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
-- coding: utf-8 --
def normalize(name): return name.capitalize()
测试:
L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2)
#请编写一个prod()函数,可以接受一个list并利用reduce()求积:
-- coding: utf-8 --
from functools import reduce
def prod(L): def pow1(x,y): return x*y return reduce(pow1,L)
print('3 5 7 * 9 =', prod([3, 5, 7, 9])) if prod([3, 5, 7, 9]) == 945: print('测试成功!') else: print('测试失败!')
#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
-- coding: utf-8 --
from functools import reduce
def str2float(s):
print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!')