Discuss / Python / 练习3

练习3

Topic source

from functools import reduce def str2float(s): l = s.split(".") if len(l) != 2: return reduce(lambda x,y:x10+y, [ord(x)-ord('0') for x in l[0]]) / 1.0 zhengshu = reduce(lambda x,y:x10+y, [ord(x)-ord('0') for x in l[0]]) if l[0] != '' else 0 xiaoshu = reduce(lambda x,y:x+y/10.0, [ord(x)-ord('0') for x in l[1]]) if l[1] != '' else 0 xiaoshu /= 10.0 return zhengshu + xiaoshu

str2float("123") 123.0 str2float("123.1") 123.1 str2float(".1") 0.1 str2float("0.1") 0.1

小数部分处理错了,重新修改为: def str2float(s): l = s.split(".") if len(l) != 2: return reduce(lambda x,y:x10+y, [ord(x)-ord('0') for x in l[0]]) / 1.0 zhengshu = reduce(lambda x,y:x10+y, [ord(x)-ord('0') for x in l[0]]) if l[0] != '' else 0 xiaoshu = reduce(lambda x,y:x10+y,[ord(x)-ord('0') for x in l[1]])/10.0*len(l[1]) if l[1] != '' else 0 return zhengshu + xiaoshu

str2float("123.123") str2float("123") str2float(".123")


  • 1

Reply