# -*- coding: utf-8 -*-
from functools import reduce
#利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字
#输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart'].
def normalize0(name):
def capital(str):
return str.capitalize()
return list(map(capital,name))
BIG_SMALL = {'A':'a', 'B':'b', 'C':'c', 'D':'d', 'E':'e', 'F':'f', 'G':'g', 'H':'h', 'I':'i', 'J':'j', 'K':'k', 'L':'l', 'M':'m', 'N':'n', 'O':'o', 'P':'p', 'Q':'q', 'R':'r', 'S':'s', 'T':'t', 'U':'u', 'V':'v', 'W':'w', 'X':'x', 'Y':'y', 'Z':'z'}
SMALL_BIG = {'a':'A', 'b':'B', 'c':'C', 'd':'D', 'e':'E', 'f':'F', 'g':'G', 'h':'H', 'i':'I', 'j':'J', 'k':'K', 'l':'L', 'm':'M', 'n':'N', 'o':'O', 'p':'P', 'q':'Q', 'r':'R', 's':'S', 't':'T', 'u':'U', 'v':'V', 'w':'W', 'x':'X', 'y':'Y', 'z':'Z'}
def normalize1(L1):
L0=[]
for j,name in enumerate(L1):
value=''
for i,x in enumerate(name):
if x in BIG_SMALL:
x=BIG_SMALL[x]
if i==0:
x=SMALL_BIG[x]
value=value+x
L0.append(value)
return L0
def normalize2(name):
return list(map(lambda s:s[:1].upper() + s[1:].lower(), name))
L3 = ['adam', 'LISA', 'barT']
#L2 = list(map(normalize, L1))
#print(L2)
print(normalize0(L3))
#******************************************************************************
#******************************************************************************
#Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积.
def prod0(L):
def mul(x,y):
return x*y
return(reduce(mul,L))
def prod1(L):
return(reduce(lambda x,y:x*y,L))
print('3 * 5 * 7 * 9 =', prod1([3, 5, 7, 9]))
if prod1([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
#**************************************************************************
#**************************************************************************
#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
#不知为何错。。。。。
#def str2float0(s):
# return map(lambda s:int(s.split('.')[0])+int(s.split('.')[1])* \
# pow(10,-len(s.split('.')[1])),s)
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(c):
return DIGITS[c]
def str2float(s):
s = s.split('.')
s1 = s[0] #取整数部分
s2 = s[1:] or ['0'] #取小数部分
s2 = s2[0] or '0'
s2 = s2[::-1] #反转小数部分,以便从后往前加权求和
return (reduce(lambda x, y: x * 10 + y, map(char2num, s1))) + (reduce(lambda x, y: x / 10 + y, map(char2num, s2))) / 10
def str2float1(s):
return reduce(lambda x, y: x + y*pow(10,-len(str(y))), map(int, s.split('.')))
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
python笔记-2
最新推荐文章于 2024-10-05 08:57:27 发布