1.
# -*- coding:utf-8 -*- def countToFour1(): for eachNum in range(5): print eachNum, def countToFour2(n): for eachNum in range(n, 5): print eachNum, def countToFour3(n=1): for eachNum in range(n, 5):m print eachNum, def tests(f): for argu in [2, 4, 5, 'nothing']: print u'%s(%s) 输出:' % (f.__name__, argu), if argu == 'nothing': try: f() print '\n' except TypeError, e: print 'ERROR: ', e print '\n' else: try: f(argu) print '\n' except TypeError, e: print 'ERROR: ', e print '\n' tests(countToFour1) tests(countToFour2) tests(countToFour3)
2.
# -*- coding:utf-8 -*- def add_product(*numpairs): result = {} for eachpair in numpairs: num1 = eachpair[0] num2 = eachpair[1] addresult = '%d + %d' % (num1, num2) proresult = '%d * %d' % (num1, num2) result[addresult] = num1 + num2 result[proresult] = num1 * num2 return result
3.
# -*- coding:utf-8 -*- def max2(a, b): return a if a > b else b def min2(a, b): return a if a < b else a def my_max(*argus): if len(argus) == 0: return u"错误!必须对非空集合取最小值!" else: maxvalue = argus[0] for eachvalue in argus: if eachvalue > maxvalue: maxvalue = eachvalue return maxvalue def my_min(*argus): if len(argus) == 0: return u"错误!必须对非空集合取最小值!" else: minvalue = argus[0] for eachvalue in argus: if eachvalue < minvalue: minvalue = eachvalue return minvalue
4-5 略
6.
7.
def my_zip(*argus): return map(None,argus[0], argus[1])
8.
# -*- coding:utf-8 -*- def year_judge(year): if (int(year) % 4 == 0 and int(year) % 100 != 0) or int(year) % 400 == 0: return True else: return False def leap_list(yearlist): return filter(year_judge, yearlist) someyears = range(1999, 2201) leapyears = [year for year in someyears if year%4==0 and year%100!=0 or year%400==0] print leapyears print leap_list(someyears)
9.
def average(nums): print reduce(lambda x, y: x+y, nums)/float(len(nums))
10. '.'的意思还是不太理解,搁置
11.
# -*- coding:utf-8 -*- import os def file_strip(filename): fobj = open(filename, 'r') content = fobj.readlines() fobj.close() #newcontent = map(lambda string: string.strip(), content) map()实现 newcontent = [string.strip() for string in content] # 列表解析 yourchoice = int(raw_input(u'覆盖原文件还是创建新文件?覆盖原文件请输入1,创建新文件输入2:'.encode('gbk'))) if yourchoice == 1: fobj = open(filename, 'w') else: file_name = os.path.splitext(filename) fobj = open(''.join((file_name[0]+'1',file_name[1])),'w') fobj.writelines(map(lambda string: string+'\n',newcontent)) #fobj.writelines(['%s\n' %eachline for eachline in newcontent]) fobj.close()
12.
import time def timeit(func, *nkwargs, **kwargs): t0 = time.clock() funcreturn = func(*nkwargs, **kwargs) result = (time.clock()-t0, funcreturn) return result
13.
a.
def mult(x, y): return x * y
b.
def mult(x, y): return x * y def factorial(n): if n <= 1: return 1 else: return reduce(mult, range(1, n+1))
c.
def factorial(n): if n <= 1: return 1 else: return reduce(lambda x, y: x*y, range(1, n+1))
d.
import test_11_12 def factorial_reduce(n): if n <= 1: return 1 else: return reduce(lambda x, y: x*y, range(1, n+1)) def factorial_recursion(n): if n <= 1: return 1 else: return n * factorial_recursion(n-1) def factorial_iteration(n): if n <= 1: return 1 else: result = 1 for num in range(1, n+1): result = result * num return result def test(n): funcs = (factorial_reduce, factorial_recursion, factorial_iteration) for eachfun in funcs: retval = test_11_12.timeit(eachfun, n) print '%s time is %s.' % (eachfun.__name__, retval[0])
14.
def Fibonacci(n): if n <= 1: return n else: return Fibonacci(n-1) + Fibonacci(n-2)
16.
#!/usr/bin/env python # -*- coding:utf-8 -*- from __future__ import division from operator import add, sub, mul from random import randint, choice def div(x, y): return x / y ops = {'+': add, '-': sub, '*': mul, '/': div} MAXTRIES = 2 def doprob(): op = choice('+-/*') nums = [randint(1, 100) for i in range(2)] nums.sort(reverse=True) ans = ops[op](*nums) pr = '%d %s %d=' %(nums[0], op, nums[1]) oops = 0 while True: try: if int(raw_input(pr)) == ans: print u'解对了' break if oops == MAXTRIES: print u'应该是:\n%s%d' % (pr, ans) break else: print u'解错了。。。再拭一次' oops += 1 except (KeyboardInterrupt, EOFError, ValueError): print u'无效输入。。。再试一次' def main(): while True: doprob() try: opt = raw_input(u'继续? [Y]'.encode('gbk')).lower() if opt and opt[0] == 'n': break except (KeyboardInterrupt, EOFError): break if __name__ == '__main__': main()