Discuss / Python / 三题总作业

三题总作业

Topic source

第一题: 方法1: def normalize(c): c = c.lower() c = c.capitalize() return c L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) 运用内置函数先将整个字符串全部改为小写,再将首字母大写

方法2: def func(c): c = c[:1].upper() + c[1:].lower() return c L1 = ['adam', 'LISA', 'barT'] L2 = list(map(func, L1)) print(L2) 将字符串分片,第一个字符改为大写,其余字符串小写

第二题: def prod(L): return reduce(lambda x, y: x * y,L) print('3 5 7 * 9 =', prod([3, 5, 7, 9])) if prod([3, 5, 7, 9]) == 945: print('测试成功!') else: print('测试失败!')

第三题: from functools import reduce DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'} def str2float(s): def fn(x, y): if y == '.': return x return x 10 + y def char2num(s): return DIGITS[s] p = len(s) - 1 - s.index('.') return reduce(fn,map(char2num,s)) / (10 ** p) print(str2float('123.456')) print(str2float('2356.15615')) 先将小数点的影响放一边,计算除去小数点的整数大小,再计算小数点位置,再计算小数点位置


  • 1

Reply