Discuss / Python / 交作业

交作业

Topic source
# -*- coding: utf-8 -*-
from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
    '8': 8, '9': 9}

def normalize(name):
    return name[0].upper() + name[1:].lower()

def prod(L):
    return reduce(lambda x, y: x * y, L)

def str2float(s):
    list = s.split('.')
    intNum = reduce(lambda x, y: x * 10 + y, map(lambda c: DIGITS[c], list[0]))
    floatNum = reduce(lambda x, y: x * 10 + y, map(lambda c: DIGITS[c], list[1]))
    return intNum + floatNum * 10 ** -len(list[1])

def main():
    print('str2float(\'123.456\') =', str2float('123.456'))
    if abs(str2float('123.456') - 123.456) < 0.00001:
        print('测试成功!')
    else:
        print('测试失败!')

if __name__ == '__main__':
    main()

  • 1

Reply