Discuss / Python / 第三题好像有点儿复杂

第三题好像有点儿复杂

Topic source

vv阿甘vv

#1 Created at ... [Delete] [Delete and Lock User]
## 第一题
def normalize(name):
    return name[0].upper() + name[1:].lower()

L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)



from functools import reduce

## 第二题

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

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')

## 第三题

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

def str2float(s):
    def char2(x):   # 返回字符串值对应的数字
        return DIGITS[x]
    def f(x, y):    # 像老师的例子一样定义一个函数
        return x * 10 + y
    n = s.index('.')  # 定位小数点的位置
    return reduce(f, map(char2, s[:n])) + reduce(f, map(char2, s[n+1:])) * 10**(-1*(len(s)-n-1))
'''
return 分成两部分看,reduce(f, map(char2, s[:n])) 这部分将整数部分计算出来,
reduce(f, map(char2, s[n+1:])) * 10**(-1*(len(s)-n-1)) 这部分将小数部分计算出来,其中
10**(-1*(len(s)-n-1)), ** 两个星号表示次方, 10**3就是10的三次方,那么只需计算一下小数点后面有几位数就知道是几次方了,
len(s)-n-1 字符长度减去小数点所在索引位置再减一就是小数部分长度,因为是小数,所以应该是负次方,再乘-1
'''


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

厉害,这个思路没想到。

贝卤卜

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

请问如果输入值没有小数点的情况也可以吗


  • 1

Reply