Discuss / Python / 交个作业。第三题稍有不同

交个作业。第三题稍有不同

Topic source

小羊飞的

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

第一题: def normalize(name): result='' result=result+name[0].upper() for i in range(1,len(name)): result = result +name[i].lower() return result 第二题: def prod(L): def plus(x,y): return x*y return reduce(plus,L) 第三题:

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

def str2float(s): digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': -1} def fn(x, y): if (y == -1): return x else: return x * 10 + y def char2num(c): return digits[c]

result = reduce(fn, map(char2num, s))
flag = 1
for i in range(len(s)-1, 0, -1):
    if (s[i] == '.'): break
    flag *= 10
return result / flag

  • 1

Reply