Discuss / Python / 高手只做难题: homework3

高手只做难题: homework3

Topic source
from functools import reduce
import math

def char2int(ch):
    return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[ch]


def str2float(s):
    index = s.find('.')
    result = reduce(lambda x,y : x*10+y, list(map(char2int, s.replace('.',''))))
    return (index == -1 and result or result / math.pow(10,len(s)-index-1))

测试: (1)print('str2float(\'123.456\') =', str2float('123.456')) str2float('123.456') = 123.456 (2)print('str2float(\'123\') =', str2float('123')) str2float('123') = 123 (3)print('str2float(\'.456\') =', str2float('.456')) str2float('.456') = 0.456 (4)print('str2float(\'0.456\') =', str2float('0.456')) str2float('0.456') = 0.456


  • 1

Reply