Discuss / Python / 我的答案,请大家指教。

我的答案,请大家指教。

Topic source

冯征sh

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

# 第一题回答

def normalize(name):

    ord_ = name[0]

    if ord_ >= 'a' and ord_ <= 'z':  # 判断首字母是否是小写

        ord_ = chr(ord(ord_) - 32)  # 将该字母通过ord转成数字-32后再通过chr转成字母即是对应的大写字母

    return ord_ + name[1:]

# 第二题回答

def prod(L):

    def mul(a, b):

        return a * b

    return reduce(mul, L)

# 第三题回答

def str2float(s):

    def mul10(x, y):

        return int(x) * 10 + int(y)

    s = list(s)

    if '.' in s:

        defcimal_poit = len(s) - s.index('.') - 1  # 计算小数点位置

        num = 10**(-defcimal_poit)  # 计算整个数去掉小数点后需乘以多少才能还原

        s.remove('.')  # 去除小数点

        result = round(reduce(mul10, s) * num,

                       defcimal_poit)  # 对计算结果按原数字小数点位数进行四舍五入,避免精度问题造成数字与原数不同

    else:

        result = reduce(mul10, s)

    return result


  • 1

Reply