Discuss / Python / 作业题

作业题

Topic source

iiliul

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

一:

#!/usr/bin/env python

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

L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

二:

#!/usr/bin/env python

from functools import reduce

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

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))

iiliul

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

三:

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]
    l = s.split('.')
    return reduce(lambda x, y: x * 10 + y, map(char2num, l[0])) + reduce(lambda x, y: x / 10 + y, map(char2num, l[1][::-1])) / 10

参考其它同学的代码,尤其是小部分做字符串反转的处理!

这段也是小数位为重复数字的时候输出有异常

str2float('0.11') 0.11000000000000001

感觉是在处理小数位的时候除10发生的变化? 改动:去掉/10 else: m=reduce(fun2,map(char2num,L[1][::-1])) n=reduce(fun1,map(char2num,L[0])) return m,n

str2float('0.11') (1.1, 0)

改动:恢复/10 else: m=reduce(fun2,map(char2num,L[1][::-1]))/10 n=reduce(fun1,map(char2num,L[0])) return m,n

str2float('0.11') (0.11000000000000001, 0)

哪位大神能帮我解释下


  • 1

Reply