Discuss / Python / 交作业

交作业

Topic source

第一题

def normalize(name):
    result = name[0].upper()
    if len(name) > 0:
        result += name[1:].upper().swapcase()
    return result

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

第二题

from functools import reduce

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

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))

第三题

from functools import reduce

def str2float(s):
    swt = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
     '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    a, b = s.split('.')
    numa = reduce(lambda x, y: x * 10.0 + y, map(lambda z: swt[z],a))
    numb = (reduce(lambda x, y: x / 10 + y, map(lambda z: swt[z],b[::-1]))) / 10
    return numa + numb

print('str2float(\'123.456\') =', str2float('123.456'))

  • 1

Reply