Discuss / Python / map,reduce函数

map,reduce函数

Topic source
# 第一道
def normalize(name):
    return name[:1].upper()+name[1:].lower()

# 第二道
def prod(L):
   return reduce((lambda x,y:x*y),L)
# 第三道
from functools import reduce
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]
def str2int(s):
    return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def str2float(s):
    s_int,s_float=s.split(".")
    return str2int(s_int+s_float)/10**len(s_float)
    
# 第三道作弊法
def str2float(s):
    s_int,s_float=s.split(".")
    return  int(s_int+s_float)/10**len(s_float)

  • 1

Reply