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
    return reduce(fn, map(str2num, s)) / pow(10,s.index('.'))

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

MR徐展

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

发现pow/s.index('.')不是很普遍,所以在大神的代码基础上稍作修改。

def str2float(s):
    def str2num(s):
        if s != '.':
            return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
        else:
            return s

    def fn(x, y):
        if x == '.':
            return y*0.1
        if y == '.':
            return x
        return x*10+y
    return reduce(fn, map(str2num, s))

str = input("请输入:")
print('str2float(%s)=' % str, str2float(
    str) / pow(10, len(str)-str.index('.')-1))

MR徐展

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

函数部分写错了。。。

def str2float(s):
    def str2num(s):
        if s != '.':
            return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
        else:
            return s

    def fn(x, y):
        if x == '.':
            return y
        if y == '.':
            return x
        return x*10+y
    return reduce(fn, map(str2num, s))

str = input("请输入:")
print('str2float(%s)=' % str, str2float(
    str) / pow(10, len(str)-str.index('.')-1))

  • 1

Reply