Discuss / Python / 练习题

练习题

Topic source

唯情恋昉

#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 mul(x, y):
        return x * y 
    return reduce(mul, L)
    
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')

练习题三

from functools import reduce

def str2float(s):
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    def char2num(s):
        return DIGITS[s]
    L = s.split('.')
    
    # '123'
    L1 = map(char2num, L[0])
    
    # 切片(对'456'(L[1])进行切片操作([::-1])为[6,5,4])
    L2 = map(char2num, L[1][::-1])
    
    # (1 * 10 + 2) * 10 + 3 = 123
    a = reduce(lambda x,y : x * 10 + y, L1)
    
    # (6 / 10 + 5) / 10 + 4 = 4.56
    b = reduce(lambda x,y : x / 10 + y, L2)
    
    # 123 + 4.56 / 10 = 123.456
    return a + b / 10
    
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

  • 1

Reply