Discuss / Python / 交作业(看见自己一次性写完而且还测试通过就很爽!!!!!哈哈哈哈哈)

交作业(看见自己一次性写完而且还测试通过就很爽!!!!!哈哈哈哈哈)

Topic source

I-cpp

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

首先是第一题:

def normalize(name):

if not isinstance(name, str):
    print("TypeError")
return name.capitalize()

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

测试结果: ['Adam', 'Lisa', 'Bart']

然后是第二题: from functools import reduce

def prod(L): if not isinstance(L, list): print("TypeError")

def f(x, y):
    return x * y

return reduce(f, L)

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

测试结果: 3 5 7 * 9 = 945 测试成功!

然后是第三题: from functools import reduce

def str2float(s):

if not isinstance(s, str):
    print("TypeError")
count = 0
for i in range(len(s)):
    if s[i] != '.':
        count += 1
    else:
        break
a = [x for x in s if x != '.']

def s_2_f(x):
    t = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return t[x]

def ff(x, y):
    return 10 * x + y

b = map(s_2_f, a)
c = float(reduce(ff, list(b))/ (10 ** count))

return c

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

测试结果: str2float('123.456') = 123.456 测试成功!

I-cpp

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

第三题是有错误的

测试 15926.3 输出的是1.59263

于是修改 c = float(reduce(ff, list(b))/ (10 ** count))

修改为: c = float(reduce(ff, list(b)) / (10 ** (len(s) - count - 1)))

再次测试: print('str2float(\'15926.3\') =', str2float('15926.3')) print('str2float(\'1555.22\') =', str2float('1555.22'))

输出结果:

str2float('15926.3') = 15926.3 str2float('1555.22') = 1555.22

测试成功。


  • 1

Reply