Discuss / Python / map/reduce第三题

map/reduce第三题

Topic source

landingguymmm

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

第三题:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:

# -*- 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 char2num(s):

        return DIGITS[s]

    return reduce(lambda x,y: x*10+y, map(char2num, s.replace('.','')))/(10**(len(s)-s.find('.')-1))


  • 1

Reply