Discuss / Python / 第三题作业

第三题作业

Topic source

望君佳

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

第三题编程记录

# -*- 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}
    def str2num(s):
        return digits[s]
    s = s.split('.')
    
    s1 = reduce(lambda x,y:x*10+y, map(str2num,s[0]))
    s2 = reduce(lambda x,y:x*10+y, map(str2num,s[1]))/(10**len(s[1]))
    return s1 + s2

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


  • 1

Reply