Discuss / Python / 第三题:三行代码

第三题:三行代码

Topic source

奔奔强

#1 Created at ... [Delete] [Delete and Lock User]
def str2float(s):
    point= s.index('.')
    news = s.replace('.','')
    return reduce(lambda x,y:x+y,map(lambda x:int(x)*10**(point-news.index(x)-1),news))

奔奔强

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

错误更正:

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))

奔奔强

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

写成一行,展现下函数式的简洁。

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('.','')))))

你这个思路挺好,但是有个bug就是当字符串为3333.222时,调用函数输出的值为3333.2219999999998

我打印了一下运算过程,发现是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

Reply