Discuss / Python / 题目

### 题目

Topic source

#### 露心

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

### 1

``````#编写map/reduce 函数测试
def normalize(name):
return name[:1].upper()+name[1:].lower()

# 测试:
L2 = list(map(normalize, L1))
print(L2)
``````

### 2

``````#Python提供的sum()函数可以接受一个list并求和，请编写一个prod()函数，可以接受一个list并利用reduce()求积：
from functools import reduce
def prod(L):
return x * y

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

### 3

``````#利用map和reduce编写一个str2float函数，把字符串'123.456'转换成浮点数123.456

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):
def ch(ch):
return DIGITS[ch]
index = s.find('.')
#return reduce(lambda x, y:x * 10 + y, map(ch,s[:index]))+0.1*reduce(lambda x, y: x / 10 + y, map(ch, s[index+1:][::-1]))
return reduce(lambda x, y:x * 10 + y, map(ch,s[:index]))+0.1*reduce(lambda x, y: x / 10 + y, map(ch, s[len(s) - 1 : index:-1]))

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

#### 胖头鱼

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

• 1