Discuss / Python / 第二天开始

第二天开始

Topic source

问题一: def normalize(name): first = name[:1].upper() second = name[1:].lower() return first + second

问题二: def prod(L): def mul(x,y): return x * y return reduce(mul,L)

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0, '.': 0}
def char2num(s):
    return DIGITS[s]
def str2int(x,y):
    return x * 10 + y
def str2dec(x,y):
    return x / 10 + y
def divide(s):
    i = 0
    for p in s:
        if (p == '.'):
            break
        i += 1
    x = s[:i]
    y = s[:i-1:-1]
    return x, y
inte, dec = divide(s)
return reduce(str2int, map(char2num, inte))  + reduce(str2dec, map(char2num, dec))

刚刚没看到第三题,但是感觉自己写的有点略长了。主要是在分块上面写的有点多。正在考虑什么办法可以缩减一下。
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0, '. ': 0}
def char2num(s):
    return DIGITS[s]
def str2int(x,y):
    return x * 10 + y
def str2dec(x,y):
    return x / 10 + y
inte ,dec = s.split('.',1)
return reduce(str2int, map(char2num, inte))  + reduce(str2dec, map(char2num, dec[::-1])) * 0.1

用了split()函数后感觉短多了

  • 1

Reply