Python核心编程v2.0 第11章习题答案

来源:互联网 发布:新媒体矩阵是什么 编辑:程序博客网 时间:2024/06/01 08:09

1.
input = 2:ERROR ; 2,3,4 ; 2,3,4
input = 4 : ERROR ; 4 ;4
input = 5 : ERROR ; None ; None

2.
不明白啥是产物,故保留了加法式子

# -*- coding: utf-8 -*-def fun1(li,li2):    re = {}    for i in range(len(li)):        re[str(li[i])+'+'+str(li2[i])] = li[i]+ li2[i]    return  reif __name__ == '__main__':    li =  [1,2,3,4]    li2 = [5,6,7,8]    re = fun1(li,li2)    for eachkey in re:        print eachkey,re[eachkey]

结果:

4+8 122+6 83+7 101+5 6

3.
a,b写在一起了,b用到了非关键字可变长参数来接收当输入是参数集合的情况

# -*- coding: utf-8 -*-def max2(num,num2):    if num >= num2:        return num    else:        return num2def min2(num,num2):    if num <= num2:        return num    else:        return num2def my_max(lis,*therest):    #判断传入的参数1是不是list,按list比较    if isinstance(lis,list):        temp = lis[0]        for i in lis:            if temp < i:                temp = i        return temp    #传入的是参数集合,按参数集合比较    else:        temp = lis        for i in therest:            if temp < i:                temp = i        return tempdef my_min(lis,*therest):    if isinstance(lis,list):        temp = lis[0]        for i in lis:            if temp > i:                temp = i        return temp    else:        temp = lis        for i in therest:            if temp > i:                temp = i        return tempif __name__ == '__main__':    print my_max([1,3,4,5])    print my_min([2,4,1,7])    print my_max(['wqe','rd','wes'])    print my_max(1,3,4,2)

4.

# -*- coding: utf-8 -*-def turning(fen):    h = fen / 60    m = fen % 60    return h,mif __name__ == '__main__':    fen = 75    (h,m) = turning(fen)    print h,m

5.
设置一个默认参数即可,形如tax = 0.75

6.
翻译过来的中文怎么看着这么奇怪,经常不能理解到底在说啥。

# -*- coding: utf-8 -*-def turning(s,*arg):    #注意不要写成字符串形式了    print s % argif __name__ == '__main__':    turning('%d and %d',7,9)

7.

if __name__ == '__main__':    li1 = [1,2,3]    li2 = ['a','b','c']    li3 = []    map(lambda x,y:li3.append((x,y)),li1,li2)    print zip(li1,li2)

8.

# -*- coding: utf-8 -*-def func(year):    if year % 4 == 0 and year % 100 != 0:        return 1    elif year % 400 == 0:        return 1    else:        return 0if __name__ == '__main__':    list = [2010,2016,1994]    li = filter(func,list)    li2 = [n for n in list if func(n) == 1]

9.
reduce的效果是list[0]与list[1]经过func 产生一个结果,然后这个结果再和list[3]进行func,依次向后进行

# -*- coding: utf-8 -*-def average(num):    su = reduce(lambda x, y: x + y, num)    ave = su/len(num)    return  aveif __name__ == '__main__':    num = [1,2,3,4,5]    print average(num)

10.
os.listdir 列出指定目录的文件,filter返回不包括这两个特殊目录的其余文件

11.

# -*- coding: utf-8 -*-def cleanfile(lines):    li = map(lambda x:x.strip(),lines)    #列表解析    #li = [x.strip() for x in lines]    return liif __name__ == '__main__':    order = raw_input('new or old')    name = raw_input('filename')    f = open(name, 'r')    lines = f.readlines()    f.close()    li = cleanfile(lines)    if order == 'new':        file2 = raw_input('newfile')    else:        file2 = name    f = open(file2, 'w')    for i in li:        f.write(i)        f.write('\n')    f.close()

12.
time.clock返回当前的cpu时间

# -*- coding: utf-8 -*-import timedef testit(func,*arg):    t0 = time.clock()    re = func(*arg)    t1 = time.clock()-t0    return re,t1if __name__ == '__main__':    funcs = (int,float)    vals = ('123',123)    for eachfunc in funcs:        print '__________'        for eachval in vals:            retval = testit(eachfunc,eachval)            print 'result: ',retval[0]            print 'time:',retval[1]

13.

# -*- coding: utf-8 -*-import timedef mult(x,y):    return x*ydef factorial(n):    if n == 0 or n == 1:        return 1    else:        return (n*factorial(n-1))def testit(func,*arg):    t0 = time.clock()    re = func(*arg)    t1 = time.clock()-t0    return re,t1if __name__ == '__main__':    li = range(1,6)    # re = reduce(mult,li)    re = testit(reduce,mult,li)    # re2 = reduce(lambda x,y:x*y,li)    re2 = testit(reduce,lambda x,y:x*y,li)    # re3 = factorial(5)    re3 = testit(factorial,5)    print re    print re2    print re3

结果:
lambda的用时应该是最少的

(120, 5.598383186935613e-06)(120, 9.33063864489268e-07)(120, 1.555106440815449e-06)

14.

# -*- coding: utf-8 -*-def f(n):    if n == 1:        return 1    elif n == 2:        return 1    else:        return f(n-1)+f(n-2)if __name__ == '__main__':    print f(5)

15.
f 接收开始打印的位置

# -*- coding: utf-8 -*-def f(n):    #如当前n未到末尾则打印当前并从n+1位置再进行函数    if n + 1< len(str):        print str[n]        f(n+1)    #已到达字符串末尾    else:        print str[n]if __name__ == '__main__':    str = 'this is a string'    f(0)

16.
除法用的真实除法,单独做了处理

# -*- coding: utf-8 -*-from __future__ import  divisionfrom operator import add,sub,mulfrom random import randint,choiceops = {'+':add,'-':sub,'*':mul}def doprob():    op = choice('+-*/')    nums = [randint(1,10) for i in range(2)]    nums.sort(reverse=True)    if op == '/':        ans = nums[0]/nums[1]    else:        ans = ops[op](*nums)    print '%d %s %d' % (nums[0],op,nums[1])    print '= ',ansif __name__ == '__main__':    doprob()

17.
a)currying:将函数式编程的概念与默认参数以及可变参数结合在一起,一个带n个参数,curried的函数固化第一个参数为固定参数,并返回一个带n-1个参数的函数对象。
currying能泛化成为PFA。PFA将任意数量的参数的函数转化为另一个带剩余参数的函数对象
b)闭包:如果在一个内部函数里,对在外部作用域(但不是全局作用域)的变量进行引用,则内部函数就被认为是闭包。闭包和函数调用没什么关系,而是关于使用定义在其他作用域的变量。
c)生成器:挂起返回出中间值并多次继续的协同程序
迭代器:调用获得下个元素next()

18.

# -*- coding: utf-8 -*-import threadingimport timelock = threading.Lock()su = 100def deco(func):    def _deco(money):        lock.acquire()        ret = func(money)        lock.release()        return ret    return _deco@decodef funk(money):    global su    su = su + money    return suclass MyThread(threading.Thread):  # 使用类定义thread,继承threading.Thread    def __init__(self, name):        threading.Thread.__init__(self)        self.name = "Thread-" + str(name)    def run(self):  # run函数必须实现        global lock # 多线程是共享资源的,使用全局变量        # time.sleep(1)        # if lock.acquire(): # 当需要独占counter资源时,必须先锁定,这个锁可以是任意的一个锁,可以使用上边定义的3个锁中的任意一个        money = funk(100)        print "I am %s, set counter:%s" % (self.name, money)        print '\n'        # lock.release()  # 使用完counter资源必须要将这个锁打开,让其他线程使用        # print lock.release()if __name__ == '__main__':    for i in xrange(1,5):        my_thread = MyThread(i)        my_thread.start()

在我机子上运行没出现阻塞及抢占的情况,在去掉release语句后,则只有thread 1 获得了资源永久阻塞,原理应该没错。
装饰器我现在的理解大概是在处理调用某函数时,自动做一些事情,并在函数结束后也可以设置再做一些处理。