Discuss / Python / 交作业【1、2、3题】

### 交作业【1、2、3题】

Topic source

#### 做回自己ZXH

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reduce
def normalize(name):
return str.title(name)
# 测试:
L2 = list(map(normalize, L1))
print(L2)

def prod(L):
def f1(x,y):
return x*y
return reduce(f1,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
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2float(s):
num_str = '' #num_str记录数字（字符串格式）
for i in range(len(s)):
if s[i] == '.':
p = i + 1 #p记录小数点的位置
else:
num_str = num_str + s[i]
def char2num(v):
return digits[v]
def f2(m,n):
return m*10+n
num_int = reduce(f2, map(char2num, num_str)) #num_int记录数字（整数格式）
return num_int / 10 ** (len(s) - p)
# 测试:
print('str2float(\'123.456\') =', str2float('123.456'))
print('str2float(\'12.3456\') =', str2float('12.3456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')


• 1