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

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  re


if __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 12
2+6 8
3+7 10
1+5 6

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

# -*- coding: utf-8 -*-
def max2(num,num2):
    if num >= num2:
        return num
    else:
        return num2

def min2(num,num2):
    if num <= num2:
        return num
    else:
        return num2

def 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 temp


def 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 temp

if __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,m
if __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 % arg

if __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 0

if __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  ave
if __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 li

if __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 time
def testit(func,*arg):
    t0 = time.clock()
    re = func(*arg)
    t1 = time.clock()-t0
    return re,t1

if __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 time

def mult(x,y):
    return x*y

def 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,t1

if __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  division
from operator import add,sub,mul
from random import randint,choice

ops = {'+':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 '= ',ans

if __name__ == '__main__':
    doprob()

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

18.

# -*- coding: utf-8 -*-
import threading
import time

lock = threading.Lock()
su = 100


def deco(func):
    def _deco(money):
        lock.acquire()
        ret = func(money)
        lock.release()
        return ret
    return _deco

@deco
def funk(money):
    global su
    su = su + money
    return su



class 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 获得了资源永久阻塞,原理应该没错。
装饰器我现在的理解大概是在处理调用某函数时,自动做一些事情,并在函数结束后也可以设置再做一些处理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值