第三题:三行代码
Topic source错误更正:
def str2float(s):
point= s.index('.')
news = list(enumerate(s.replace('.','')))
return reduce(lambda x,y:x+y,map(lambda x:int(x[1])*10**(point-x[0]-1),news))
写成一行,展现下函数式的简洁。
def str2float(s):
return reduce(lambda x,y:x+y,map(lambda x:int(x[1])*10**(s.index('.')-x[0]-1),list(enumerate(s.replace('.','')))))
我打印了一下运算过程,发现是python的浮点数运算导致的,看最后一步。
x= 3000 y= 300 x+y= 3300
x= 3300 y= 30 x+y= 3330
x= 3330 y= 3 x+y= 3333
x= 3333 y= 0.2 x+y= 3333.2
x= 3333.2 y= 0.02 x+y= 3333.22
x= 3333.22 y= 0.002 x+y= 3333.2219999999998
- 1
奔奔强