Discuss / Python / 第三题

第三题

Topic source

南小i

#1 Created at ... [Delete] [Delete and Lock User]
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    def fn(x1, x2):
        return x1*10 + x2
    def char2num(c):
        return DIGITS[c]
    s1 = s[:s.find('.')]
    s2 = s[s.find('.')+1:]
    v1 = reduce(fn, map(char2num, s1))
    v2 = reduce(fn, map(char2num, s2))
    for n in range(len(s2)):
        v2 = v2 * 0.1
    return v1 + v2

南小i

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

或者用split

    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    def char2num(c):
        return DIGITS[c]
    s1, s2 = s.split('.')
    v1 = reduce(lambda x1, x2: x1 * 10 + x2, map(char2num, s1))
    v2 = reduce(lambda x1, x2: x1 * 10 + x2, map(char2num, s2))
    for n in range(len(s2)):
        v2 = v2 * 0.1
    return v1 + v2

  • 1

Reply