Discuss / Python / 三题作业做完 -----小帅

三题作业做完 -----小帅

Topic source

yayayaxs

#1 Created at ... [Delete] [Delete and Lock User]

第一题: 把列表中的每一个名字发送到normalize函数中,然后利用name[0].upper()把首字母变成大写,用name[1:].lower()把后面的字母变成小写

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

def normalize(name):
    rerurn name[0].upper() + name[1:].lower()

list(map(normalize, ['adam', 'LISA', 'barT']))

第二题:

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

from functools import reduce

def prod(L):
    def product(x, y):
        return x * y
     rerurn reduce(prod, L)

print (prod(L))

第三题:

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

from functools import reduce

def str2float(s):
    def char2num(s):
        return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[s]
    def fn(x, y):
        return x * 10 + y
    n = s.index('.')
    return reduce(fn, map(char2num, s[0:n] + s[n+1:])) / (10**n)

print('str2float(\'123.456\') =', str2float('123.456'))

是不是应该这样呢

def str2float(s):
    def char2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    def fn2(x, y):
        return x * 10 + y
    n = s.index('.')
    p = len(s) - n -1
    return reduce(fn2, map(char2num, s[:n] + s[n+1:])) / (10**p)

5080sy

#3 Created at ... [Delete] [Delete and Lock User]

上面的朋友已经改正了第三题的答案

我再稍微给迷糊的同学补充一下:

from functools import reduce
def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.':'.'}[s]
def f(x, y):
    return x*10 + y
def str2float(s):
    i = s.index('.')    # i是s中'.'的下标(位置), 也代表了小数点前数字的个数
    ss = s[:i] + s[i+1:]
    return reduce(f, map(char2num, ss)) / 10**(len(ss)-i)    # (len(ss)-i) 是 s 中的小数点之后数字的个数, 即幂的指数
print('str2float(\'23333.456\') =', str2float('23333.456'))

yayayaxs

#4 Created at ... [Delete] [Delete and Lock User]

对对对,粗心了,后面两句应该改为:

n = s.index('.')
    p = len(s) - n -1
    return reduce(fn2, map(char2num, s[:n] + s[n+1:])) / (10**p)

  • 1

Reply