Discuss / Python / 作业

作业

Topic source

祥子920

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

#!/usr/bin/env python3

# -*- 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, '.': 10}

#用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字    

def normalize(name):

    return name.capitalize()

def fn(x, y):

    return x * y   

#接受一个list并求积    

def prod(L):

    return reduce(fn, L)

#字符串转换成浮点数  

def str2float(s):

    flag = 0

    def fn(x, y):

        nonlocal flag 

        if y == 10:

            flag = 1

            return x

        if flag == 0:

            return x * 10 + y

        else:

            for n in range(0, flag):

                y = y * 0.1

            flag = flag + 1

            return  x + y

    def char2num(s):

        return DIGITS[s]

    return reduce(fn, map(char2num, s))    

利用了一个没学的标志位,作为整数和小数的切换,代码不够优雅,还需进步

  • 1

Reply