Discuss / Python / 交作业

交作业

Topic source

第一题

# _*_ coding : UTF-8 _*_
# 2020/4/5
# map/reduce 练习1
# 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
def normalize (name) :
    if not isinstance (name,str) :
        raise TypeError ('***参数不是字符串***')
    name1 = name[0].upper()   #name的首字母大写(这里输出只有首字母)
    name2 = name[1:].lower()  #name的除首字母以后全部小写(输出只有除首字母的部分)
    name = name1 + name2      #所以要连起来重新赋值给name
    return name

第二题

# _*_ coding : UTF-8 _*_
# 2020/4/5
# map/reduce 练习2
# 编写一个prod()函数,可以接受一个list并利用reduce()求积
def prod (L) :
    from functools import reduce         #调用reduce函数
    return reduce(lambda x, y : x * y , L)   #定义prod

第三题

# _*_ coding : UTF-8 _*_
# 2020/4/5
# map/reduce 练习3
# 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456
# 等价于定义 float()
def str2float(s) :
    from functools import reduce         #调用reduce函数
    DIGITS = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
    def char2num(s) :               #定义把数字字符元素转为数字元素的函数
            return DIGITS[s]
    i = s.find('.')            #找到'.'所在的索引位
    L1=reduce(lambda x,y:x*10+y,map(char2num,s[:i]))  #取'.'之前的元素计算
    L2=reduce(lambda x,y:x/10+y,map(char2num,s[:i:-1]))/10  #取'.'之后的元素计算
    return L1 + L2

第三题你写得好棒,学习了


  • 1

Reply