Discuss / Python / 第三题

第三题

Topic source
from functools import reduce 
def str2float(s):
    def str2num(s):
        r = {'.':-1, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        return r[s]
    def fn(x, y):
        if x < 0:
            return y
        if y < 0:
            return x
        return x * 10 + y
    def flag(s):
        count = 1
        i = 0
        while i < s.index('.'):
            i = i + 1
            count = 10 * count
        return count
    return reduce(fn, map(str2num, s)) / flag(s)

print('str2float(\'123.456\')=', str2float('123.456'))

用pow()函数代替了flag函数,代码更简洁

from functools import reduce 
def str2float(s):
    def str2num(s):
        r = {'.':-1, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        return r[s]
    def fn(x, y):
        if x < 0:
            return y
        if y < 0:
            return x
        return x * 10 + y
    return reduce(fn, map(str2num, s)) / pow(10,s.index('.'))

print('str2float(\'123.456\')=', str2float('123.456'))

发错地方了 不好意思


  • 1

Reply