Discuss / Python / 第三题

第三题

Topic source

-- coding: utf-8 --

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, '.': 10} n = 0 def yunsuan(x, y) : nonlocal n if y != 10 and n == 0 : return x10+y if y == 10 : n = 1 return x for i in range(n) : y = y0.1 n = n + 1 return x + y def charToInt(char) : return DIGITS[char] return reduce(yunsuan, map(charToInt, s))

print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: 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,'.':10.0} n=-1

def str2float(s):

def fn(x,y):
    global n
    w=0
    if y!=10.0 and n==-1:
        return x*10+y
    elif y==10.0:
        n=0
        return x
    elif n>=0:
        n=n+1
        return x+(y*(10**(-n)))


def char2num(s):
    return DIGITS[s]
return reduce(fn,map(char2num,s))

print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) >=0.00001: print('测试成功!') else: print('测试失败!')


  • 1

Reply