Discuss / Python / 第三题琢磨了一个自己的解法

第三题琢磨了一个自己的解法

Topic source

越聊越hi

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
from functools import reduce

def dot(s):
        return 10**(len(s)-s.index('.')-1)

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

def str2float(s):
        if '.' in s:
                t = s[:s.index('.')]+s[s.index('.')+1:]
                return reduce(lambda x,y:x * 10+ y,map(char2num,t)) / dot(s)

        else:
                print('字符串中不含小数点')

print('str2float(\'1357.4576\') =', str2float('1357.4576'))

  • 1

Reply