Discuss / Python / 交作业

### 交作业

Topic source

#### chengww5217

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

# -*- coding: utf-8 -*-
def normalize(name):
return name[:1].upper() + name[1:].lower()
# return name.capitalize()


2.Python提供的sum()函数可以接受一个list并求和，请编写一个prod()函数，可以接受一个list并利用reduce()求积：

# -*- coding: utf-8 -*-
from functools import reduce
def prod(L):
return reduce(fn, L)

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

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


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

# -*- coding: utf-8 -*-
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, '.' : '.'}
aMap = map(lambda n : digits[n], s)
aList = list(aMap)
indexPoint = -1
try:
indexPoint = s.index('.')
aList.pop(indexPoint)
except ValueError:
pass
aInt = reduce(lambda x, y: 10*x + y, aList)
if indexPoint < 0:
return aInt
aFloat = aInt / (10 ** (len(s) - 1 - indexPoint))
return aFloat

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


• 1