Discuss / Python / 第三题的一种尝试

第三题的一种尝试

Topic source

tabbar

#1 Created at ... [Delete] [Delete and Lock User]
def str2float(s):
    import functools
    temp_s = s if '.' in s else s+'.'
    d, f = temp_s.split('.')
    return functools.reduce(lambda x,y: x*10 + y, map(int, d), 0) + \
           functools.reduce(lambda x,y: x/10 + y, map(int, reversed('0'+f)), 0)

print(str2float('345.678'))       # 345.678
print(str2float('0'))             # 0.0
print(str2float('123.456'))       # 123.456
print(str2float('123.45600'))     # 123.456
print(str2float('0.1234'))        # 0.1234
print(str2float('.1234'))         # 0.1234
print(str2float('120.0034'))      # 120.0034
print(str2float('.'))             # 0.0

-李铁蛋_

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

reduce里map()后面加的0是什么意义呢,是作为y吗?

-李铁蛋_

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

终于在网上找到了对应的讲解:

lst = [1,2,3,4,5]  
print reduce(lambda x,y:x+y,lst,0)

这种方式用lambda表示当做参数,因为指定了reduce的第三个参数为0,所以第一次执行时x=0,y=1,第二次x=0(x1)+1(y1),y=2

WOWsapling

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

基于此改了一下

def str2float(s):
    s_sp = s.split('.')
    return reduce(lambda x, y : x*10 + y,map(int, s_sp[0])) \
         + reduce(lambda x, y : x/10 + y,map(int, s_sp[1][::-1]))/10

WOWsapling

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

发现我改的还存在问题,继续。

WOWsapling

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

大体上都差不多。

def str2float(s):
    temp_s = s if '.' in s else s+'.'
    d, f = temp_s.split('.')    
    return reduce(lambda x, y : x*10 + y, map(int, d), 0) \
         + reduce(lambda x, y : x/10 + y,map(int, f[::-1]), 0)/10

  • 1

Reply