Discuss / Python / 高级函数(map,reduce)

高级函数(map,reduce)

Topic source

#The first question

def normalize(name):
    return name[0].upper()+name[1:].lower()

#The second question

def prod(L):
    def multip(x, y):
         return x * y
    return reduce(multip, L)

#The third question

def str2float(s):
    s0,s1 = s.split('.')
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return DIGITS[s]
    return reduce(fn, map(char2num, s0))+(reduce(fn, map(char2num, s1))/10**len(s1))

  • 1

Reply