Discuss / Python / 交作业

交作业

Topic source

1.利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: def normalize(name): return name.capitalize()

2.Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:

-- coding: utf-8 --

from functools import reduce def prod(L): def mul(x,y): return x*y return reduce(mul,L)

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} L=s.split(".") def char2int(c): return digits[c] def add(x,y): return x10+y n=len(L[1]) return reduce(add,map(char2int,L[0]))+reduce( add,map( char2int,L[1] ) )pow(10,-n) 法2 digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} L=s.split(".") def char2int(c): return digits[c] def add(x,y): return x*10+y def xiaoshu(a): while a>=1: a=a/10 return a return reduce(add,map(char2int,L[0]))+xiaoshu(reduce( add,map( char2int,L[1] ) ))


  • 1

Reply