1.给一个错乱的圣诞树重新排序
输入为:
tree = [ " * ", " * ", "*** ", " *****", " *******", "*********", " *** " ]则函数的输出为:
fixTree(tree) = [ " * ", " * ", " *** ", " ***** ", " ******* ", "*********", " *** " ]示例代码如下:
def fixTree(tree): return map(lambda x:x.strip().center(len(x)),tree)主要是字符串的
center方法.1
2.列表顺序求和
对于给定的整数列表顺序求和生成新的列表。例,
a=[1,2,3]则其输出为prefSum(a)=[1,3,6].解释:[1,1+2,1+2+3].
示例代码如下:def prefSum(a): return reduce(lambda c,x:c+[c[-1]+x],a,[0])[1:]主要是对
reduce方法的掌握,reduce(function, iterable[, initializer]),参考2、3.
3.整数列表实现相应操作
对于给定的整数列表实现相应的操作,例如,
a=[1,2,3,4,5],编程实现,sum(a)=((a[0]+a[1])*a[2]+a[3])...,对于a则输出为sum(a)=((1+2)*3+4)*5=65.
示例代码如下:def mathPractice(numbers): return reduce(lambda a,x:a+x[1] if x[0]%2!=0else a*x[1],enumerate(numbers),1)主要是
reduce函数的使用。
4.计算两个整数之间素数的和
例如
a=10,b=20则,primeSum(a,b)=60即,11+13+17+19=60,示例代码如下:def primesSum(a, b): return sum(filter(lambda x:all(x % i for i in range(2, int(x**0.5) + 1)),range(max(a,2),b+1)))主要是
all函数的使用.4
refer
1 http://www.runoob.com/python/att-string-center.html
2 https://docs.python.org/2/library/functions.html#reduce
3 http://blog.youkuaiyun.com/SeeTheWorld518/article/details/46975857
4 http://www.pythontab.com/html/2013/hanshu_0116/135.html
本文提供了一系列Python编程挑战,包括修复错乱的圣诞树显示、列表的顺序求和、数学表达式的计算以及素数之和的计算等,通过这些挑战加深对Python中字符串处理、列表操作、lambda表达式及reduce函数的理解。
273

被折叠的 条评论
为什么被折叠?



