Discuss / Python / 第三题答案

第三题答案

Topic source

葛斯特

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

!/usr/bin/env python3

-- coding: utf-8 --

from functools import reduce def str2float(s): def char2num(c): return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[c]

return reduce(lambda x, y: x * 10 + y, map(char2num, s[:s.find('.')])) + reduce(lambda x, y: x / 10 + y, map(char2num, s[-1:s.find('.'):-1]+'0'))

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

葛斯特

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

重新修改了一下

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
    def char2num(c):
        return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[c]

    return reduce(lambda x, y: x * 10 + y, map(char2num, '0'+s[:s.find('.')])) + reduce(lambda x, y: x / 10 + y, map(char2num, s[-1:s.find('.'):-1]+'0'))
print('str2float(\'1203.4506\') =', str2float('1203.4506') )
print('str2float(\'1.2\') =', str2float('1.2') )
print('str2float(\'123.456\') =', str2float('123.456') )

葛斯特

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

最终版

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
    def char2num(c):
        return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[c]
    def carry(x, y):
        return x * 10 + y
    nums = s.split('.')
    return reduce(carry, map(char2num, nums[0])) + (reduce(carry, map(char2num, nums[1])) / pow(10, len(nums[1])) if len(nums) > 1 else 0)
print('str2float(\'1203.4506\') =', str2float('1203.4506') )
print('str2float(\'1.2\') =', str2float('1.2') )
print('str2float(\'12\') =', str2float('12') )
print('str2float(\'1\') =', str2float('1') )
print('str2float(\'0.456\') =', str2float('0.456') )

  • 1

Reply