Discuss / Python / 3道练习题答案

3道练习题答案

Topic source
#利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
#输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
def test(name):
	def normalize(x):
		return x[0].upper()+(x.lower())[1:]
	return list(map(normalize,name))
#Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积
def prod(lists)
	def chengji(x,y):
		return x*y
	return reduce(chengji,lists)
#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
from functools import reduce
def str2float(s):
	s1,s2=s.split('.')#分为‘123’和‘456’
	def char2num(str):#str转化为整数
		digits={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
		return digits[str]
	def hebing(x,y):
		return x*10+y
	def hebingfloat(x,y):#这个0.1会翻转数字 所以提前先用[::-1]翻转一下
		return x*0.1+y
	s1Int=reduce(hebing,map(char2num,s1))
	#map(char2num,s2)得出456整数迭代器 转化成list(好用[::-1]翻转一下)再使用hebingfloat 记得s2是小数部分(*0.1),
	s2Float=reduce(hebingfloat,list(map(char2num,s2))[::-1])*0.1
	return s1Int+s2Float

大侠,您的这段代码def prod(lists)后面少了一个冒号

def prod(lists)
	def chengji(x,y):
		return x*y
	return reduce(chengji,lists)

  • 1

Reply