《Python核心编程》第二版第308页第十一章练习 续一 Python核心编程答案自己做的

本博客列出的答案不是来自官方资源,是我自己做的练习,如果有疑问或者错误,欢迎讨论。
原书(英文版)作者的blog :)
http://wescpy.blogspot.ca/

11-7.
用map()进行函数式编程。给定一对同一大小的列表,如[1, 2, 3, ...]和['abc', 'def', 'ghi', ...],将两个列表归并为一个由每个列表元素组成的元组的单一列表,以使我们的结果看起来像这样:{[(1, 'abc'), (2, 'def'), (3, 'ghi'), ...}。(虽然这问题在本质上和第6章的一个问题类似,那时两个解没有直接的联系)然后创建用zip内建函数创建另一个解。
【答案】
代码如下:

>>> listA = [1, 2, 3, 4]
>>> listB = ['abc', 'def', 'ghi', 'jkl']

>>> map(None, listA, listB)
[(1, 'abc'), (2, 'def'), (3, 'ghi'), (4, 'jkl')]
>>> zip(listA, listB)
[(1, 'abc'), (2, 'def'), (3, 'ghi'), (4, 'jkl')]
>>>

11-8.
用filter()进行函数式编程,使用练习5-4你给出的代码来决定闰年。更新你的代码以便使它成为一个函数,如果你还没有那么做的话。然后写一段代码来给出一个年份的列表并返回一个只有闰年的列表。然后将它转化为用列表解析。
【答案】
代码如下:

from random import randint 

def leapYear(year):
    a4 = year % 4
    a100 = year % 100
    a400 = year % 400
    if (a4 == 0 and a100 != 0) or a400 == 0: 
        return True
 
yearList = []
for eachYear in range(20):
    yearList.append(randint(1000, 2051))

print filter(leapYear, yearList)
# From www.cnblogs.com/balian/

11-9.
用reduce()进行函数式编程。复习11.7.2部分,阐述如何用reduce()计算数字集合的总和。修改它并创建一个叫average()的函数来计算每个数字集合的简单的平均值。
【答案】
根据第293页的例子,利用函数reduce()计算数字集合(列表List)的总和,可这样做:
reduce( (lambda x, y; x+y), List )
计算平均数代码如下:

>>> def average(List):
...     return reduce((lambda x,y: x+y), List)/float(len(List))
...

>>> List = range(101)
>>> print average(List)
50.0

11-10.
用filter()进行函数式编程。在unix文件系统中,在每个文件夹或者目录中都有两个特别的文件:"."表示现在的目录,".."表示父目录。给出上面的知识,看一下os.listdir()函数的文档并描述这段代码做了什么:
files = filter(lambda x: x and x[0] != '.', os.listdir(folder))
【答案】
手头没有unix系统,但在linux上面试了一下,但十分没有把握。假设folder是文件夹路径字符串‘/tmp’,os.listdir(folder)能列出文件夹/tmp的所有文件夹和文件。但题目所示的代码将把特别文件"."和".."从os.listdir的输出列表中过滤掉。等有了unix再试一下,我的想法可能不对。

11-11.
用map()进行函数式编程。写一个使用文件名以及通过除去每行中所有排头和最尾的空白来“清洁”文件。在原始文件中读取然后写入一个新的文件,创建一个新的或者覆盖掉已存在的。给你的用户一个选择来决定执行哪一个。将你的解转换成使用列表解析。
【注】附英文版题目的原文:
Functional Programming with map(). Write a program that takes a filename and “cleans” the file by removing all leading and trailing whitespace from each line. Read in the original file and write out a new one, either creating a new file or overwriting the existing one. Give your user the option to pick which of the two to perform. Convert your solution to using list comprehensions.
【答案】
代码如下:

#-*- encoding: utf-8 -*-

def CustomerChoice():
    "本函数让用户选择是创建新文件还是覆盖旧文件。"
    while True:
        print 'Please select: '
        print "To create a new 'clean' file, please input 'N'.  "
        print "To overwrite the existing file, please input 'O'.   "
        Input = raw_input('Your choice is:...  ')
        if Input == 'N':
            return True
            break
        elif Input == 'O':
            return False
            break
        else:
            print "Error input, try again.   "
            
def LineProcess(eachLine):
    eachLine = eachLine[0:-1]
    beginCharacter = eachLine[0]
    endCharacter = eachLine[len(eachLine)-1]
    while beginCharacter == ' ':
        eachLine = eachLine[1:]
        beginCharacter = eachLine[0]
    while endCharacter == ' ':
        eachLine = eachLine[:-1]
        endCharacter = eachLine[len(eachLine)-1]
    return eachLine

textFile = open('d:\sample_11_11.txt', 'r')
newLines = map(LineProcess, textFile)
print newLines
textFile.close()

customerInput = CustomerChoice()
if customerInput:   #创建一个新的干净文件
    newFile = open(r'd:\newclean.txt', 'w')
    for eachline in newLines:
        newFile.write(eachline + '\n')
    newFile.close()
else:   #覆盖原来的文件
    overwriteFile = open('d:\sample_11_11.txt', 'w')
    for eachline in newLines:
        overwriteFile.write(eachline + '\n')
    overwriteFile.close()

【注】这里假设有一个名为sample_11_11.txt的文件在D盘的根目录下。
sample_11_11.txt具体内容:
   abc   d  
  this is an sample.     
Let me try.   
  Hello world   .
  Hello world.  
Hi, man.  
【参考】
做这题我参考了下面链接:
http://bbs.chinaunix.net/thread-3605638-1-1.html

原文地址:https://www.cnblogs.com/balian/p/2620905.html