1. 程式人生 > >Python map/reduce練習(一)

Python map/reduce練習(一)

利用map和reduce編寫一個str2float函式,把字串’123.456’轉換成浮點數123.456:

from functools import reduce

def str2float(s):
    def str2num(s):
        DIGITS = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9};
        return DIGITS[s];
    def num2int(L):
        return reduce(lambda x, y: x * 10 + y,L)
    def num2float(L):
        L.reverse()
        b=[0]
        L.extend(b)
        return reduce(lambda x, y: x / 10 + y,L)
    s1 = s.split('.')[0];
    s2 = s.split('.')[1];
    s3 =(list)(map(str2num,list(s2)))
    ##round(float,num)四捨五入到小數點第幾位數字
    return num2int(map(str2num,list(s1)))+round(num2float(s3),3)

print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('測試成功!')
else:
    print('測試失敗!')

這個程式碼感覺還是不能滿足所有浮點數,只解決本題