Discuss / Python / 第三题解法

第三题解法

Topic source

弦小零

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

三道题中应该第三题稍复杂点

def str2float(s):
    dot_index = [i for i,v in enumerate(s) if v=='.'][0] # 记录'.'的索引
    def char2num(ch):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[ch]
    def str2int(s):
        return reduce(lambda x,y: x*10+y, map(char2num, s))
    return str2int(s[:dot_index])+str2int(s[dot_index+1:])*(0.1**dot_index)

看了很多评论~不知道还有没有更优的解法


  • 1

Reply