Discuss / Python / 打卡交作业,顺便推荐菜鸟教程链接

打卡交作业,顺便推荐菜鸟教程链接

Topic source

一个更基础的菜鸟教程,按版本选教程:

https://www.runoob.com/python3/python3-tutorial.html

-------------第1题-------------

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

# -*- coding: utf-8 -*-

def normalize(name):

    #列表的每个值,第1个字母大写,第2个开始都小写

 return name[0].upper()+name[1:].lower()

-------------第2题--------------

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

# -*- coding: utf-8 -*-

from functools import reduce

def prod(L):

    #reduce两个参数,一个函数实现乘积x*y,一个参数为列表L

    def f(x,y):

        return x * y

    return reduce(f,L)

-------------第3题--------------

#-*- coding: utf-8 -*-

#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456

from functools import reduce

def str2float(L):

    #把字符转成数字

    D = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

    def str2num(s):

        return D[s]

    #f,实现计算

    def f(x,y):

        return 10 * x + y

    #按小数点拆分

    c = L.index('.')

    L_int = L[:c]

    L_float = L[c+1:] 

    return reduce(f,map(str2num,L_int))+reduce(f,map(str2num,L_float))/(10**len(L_float))


  • 1

Reply