from functools import *
def Prod(s):
def char2int(s):
intList = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0}
return intList[s]
def add(x, y):
return x * 10 + y
if '.' in s:
return reduce(add, map(char2int, s.replace('.', '')))/pow(10, len(s) - s.find('.') - 1) # s.find函数可以找到字符串对应的索引
else:
return reduce(add, map(char2int, s.replace('.', '')))
题目来源于廖雪峰的网站。
map()函数:map()
函数接收两个参数,一个是函数,一个是Iterable(可迭代类型的值)
,map
将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator
返回。
reduce()函数:reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算。
pow()函数:做幂次运算,pow(x, y)表示x的y次幂。
基于map()和reduce()函数的另外两个功能:
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2int(s):
mapping = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0}
return mapping[s]
print(reduce(fn, map(char2int, s)))
def Pascal(s):
a = []
if s[0].islower():
a.append(s[0].upper())
for i in range(1, len(s)):
a.append(s[i].lower())
else:
a.append(s[0])
for i in range(1, len(s)):
a.append(s[i].lower())
new_s = "".join(a)
return new_s