Discuss / Python / 交作业

交作业

Topic source

menfrexu

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

前两题的简单点,第三题稍微难一点。

第三题基本思路:

1. 找到小数点的位置

2. 将原来的字符串去掉小数点

3. 先通过 map 将字符串转为 float

4. 通过 reduce 将字符串转为整数

5. 最后通过小数点的位置乘上 10 -n 次幂

第一题:

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

第二题:

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

第三题:

def str2float(s):
    n = 0
    result = []
    for i in range(0, len(s)):
        if s[i] == '.':
            n = i
        else:
            result.append(s[i])
    
    result = list(map(lambda x: float(x), result))
    return reduce(lambda x, y: x * 10 + y, result) * pow(10, n * -1)

grey_eyez

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

第三题是不是错了,最后不应该乘10的负n次方,应该是10的负len(s) - n + 1次方。

比如'123.4567'按照你的代码结果会是1234.567。

grey_eyez

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

啊,我了解了...好像只用针对题目样例就行了


  • 1

Reply