status |
校对 |
完成度70% |
1. 故事练习解答
1.1. CDays
1.1.1. CDays-5
- 计算今年是闰年嘛?
- 相关代码:
1 #coding:utf-8
2 '''cdays-5-exercise-1.py this year is a leap year or not
3 '''
4 #导入time模块
5 import time
6 #获取当前年份
7 thisyear = time.localtime()[0]
8 #判断闰年条件,满足模400为0,或者模4为0但模100不为0
9 if thisyear % 400 == 0 or thisyear % 4 ==0 and thisyear % 100 <> 0:
10 print 'this year %s is a leap year' % thisyear
11 else:
12 print 'this year %s is not a leap year' % thisyear
利用python作为科学计算器。熟悉Python中的常用运算符,并分别求出表达式12*34+78-132/6、(12*(34+78)-132)/6、(8.6/4)**5的值。并利用math模块进行数学计算,分别求出145/23的余数,0.5的sin和cos值等等,详细可参考help(math)。
- 相关代码:
1 #coding:utf-8
2 '''cdays-5-exercise-2.py basic operation and math library
3 '''
4 #表达式计算
5 x = 12*34+78-132/6
6 y = (12*(34+78)-132)/6
7 z = (8.6/4)**5
8 print '12*34+78-132/6 = %d' % x
9 print '(12*(34+78)-132)/6 = %d' % y
10 print '(8.6/4)**5 = %f' % z
11 #导入数学计算模块
12 import math
13 #求余函数
14 a = math.fmod(145, 23)
15 #正弦函数
16 b = math.sin(0.5)
17 #余弦函数
18 c = math.cos(0.5)
19 print '145/23的余数 = %d' % a
20 print 'sin(0.5) = %f' %b
21 print 'cos(0.5) = %f' %c
- 编写程序,在屏幕上打印出如下图案:
attachment:cdays-5-exercise-3.png
- 相关代码:
截图
1.1.2. CDays-4
os 模块中还有哪些功能可以使用? -- 提示使用 dir() help()
- os.error, os.path, os.popen, os.stat_result, os.sys, os.system等等等
详细可参见dir(os)和python帮助文档help(os)
open() 还有哪些模式可以使用?
- 'r': 以只读方式打开已存在文件,若文件不存在则抛出异常。此方式是默认方式
- 'U'或者'rU': python惯例构造了通用换行支持;提供'U'模式以文本方式打开一个文件,但是行可能随时结束:Unix的结束符规定为'\n',苹果系统则为'\r',还有windows规定为'\r\n',所有这些规定在python程序中统一为'\n'.如果python不构造一个通用换行支持模式'u'来用统一对待正常文本模式的话
- 'w': 以可写方式打开存在或者不存在的文件,若文件不存在则先新建该文件,若文件存在则覆盖该文件
- 'a': 用于追加,对unix系统而言,所有的内容都将追加到文件末尾而不管指针的当前位置如何
- 'b': 以二进制方式打开。打开一个二进制文件必须用该模式。增加'b'模式是用来兼容系统对当二进制和文本文件的处理不同
- 'r+','w+'和'a+'以更新方式打开文件(注意'w+'覆盖文件)
尝试for .. in .. 循环可以对哪些数据类型进行操作?
- for..in循环对于任何序列(列表,元组,字符串)都适用。但从广义说来可以使用任何种类的由任何对象组成的序列
- 格式化声明,还有哪些格式可以进行约定?
详细参考:[http://docs.python.org/lib/typesseq-strings.html typesseq-strings]
- d Signed integer decimal.
- i Signed integer decimal.
- o Unsigned octal.
- u Unsigned decimal.
- x Unsigned hexadecimal (lowercase).
- X Unsigned hexadecimal (uppercase).
- e Floating point exponential format (lowercase).
- E Floating point exponential format (uppercase).
- f Floating point decimal format.
- F Floating point decimal format.
- g Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise.
- G Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise.
- c Single character (accepts integer or single character string).
- r String (converts any python object using repr()).
- s String (converts any python object using str()).
- % No argument is converted, results in a "%" character in the result.
- 现在的写入文件模式好嘛? 有改进的余地?
CDay-4-5.py 好在哪里? :
CDay-4-6.py 又更加好在哪里? :
CDay-4-5.py中使用了字符串的+连接,而CDay-4-6.py中是利用join。字符串的join要比'+'操作效率高。因为对象的反复+,比一次性内建处理,要浪费更多的资源。
- 读取文件cdays-4-test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为cdays-4-result.txt。
1 #coding:utf-8
2 '''cdays-4-exercise-6.py file operation
3 '''
4 #以读方式打开文件
5 f = open('cdays-4-test.txt', 'r')
6 result = list()
7 #依次读取每行
8 for line in f.readlines():
9 #去掉每行头尾空白
10 line = line.strip()
11 #判断是否是空行或注释行
12 if not len(line) or line.startswith('#'):
13 #是的话,跳过不处理
14 continue
15 result.append(line)
16 #排序结果
17 result.sort()
18 #保存入结果文件
19 open('cdays-4-result.txt', 'w').write('%s' % '\n'.join(result))
1.1.3. CDays-3
根据 [http://www.woodpecker.org.cn/diveintopython/scripts_and_streams/command_line_arguments.html DiPy 10.6. 处理命令行参数] 使用getopt.getopt() 优化当前功能函式。
1 # coding=utf-8
2 '''Lovely Python -3 PyDay
3 PyCDC v0.3
4 '''
5 import os,sys
6 import getopt
7
8 CDROM = '/media/cdrom0'
9 def cdWalker(cdrom,cdcfile):
10 export = ""
11 for root, dirs, files in os.walk(cdrom):
12 export+="\n %s;%s;%s" % (root,dirs,files)
13 open(cdcfile, 'w').write(export)
14
15 def usage():
16 print '''PyCDC 使用方式:
17 python cdays-3-exercise-1.py -d cdc -k 中国火
18 #搜索 cdc 目录中的光盘信息,寻找有“中国火”字样的文件或是目录,在哪张光盘中
19 '''
20
21 try:
22 opts, args = getopt.getopt(sys.argv[1:], 'hd:e:k:')
23 except getopt.GetoptError:
24 usage()
25 sys.exit()
26
27 if len(opts) == 0:
28 usage()
29 sys.exit()
30
31 c_path = ''
32 for opt, arg in opts:
33 if opt in ('-h', '--help'):
34 usage()
35 sys.exit()
36 elif opt == '-e':
37 #判别sys.argv[2]中是否有目录,以便进行自动创建
38 #cdWalker(CDROM, arg)
39 print "记录光盘信息到 %s" % arg
40 elif opt == '-d':
41 c_path = arg
42 elif opt == '-k':
43 if not c_path:
44 usage()
45 sys.exit()
46 #进行文件搜索
读取某一简单索引文件cdays-3-test.txt,其每行格式为文档序号 关键词,现需根据这些信息转化为倒排索引,即统计关键词在哪些文档中,格式如下:包含该关键词的文档数 关键词 => 文档序号。其中,原索引文件作为命令行参数传入主程序,并设计一个collect函数统计关键字-序号结果对,最后在主程序中输出结果至屏幕。
1 #coding:utf-8
2 '''cdays-3-exercise-2.py using sys.args, dict and function invoke
3 '''
4 #导入sys模块
5 import sys
6
7 def collect(file):
8 ''' function collect: change the key-value to value-key
9 @param file: file object
10 @return: a dict type, get the value-key pairs
11 '''
12 result = {}
13 #依次读取每行
14 for line in file.readlines():
15 将一行以空格分割为左右两部分
16 left, right = line.split()#
17 #判断是否已经含有right值对应的key
18 if result.has_key(right):
19 #若有,直接添加到result[right]的值列表
20 result[right].append(left)
21 else:
22 #没有,则新建result[right]的值列表
23 result[right] = [left]
24 return result
25
26 if __name__ == "__main__":
27 #判断参数个数
28 if len(sys.argv) == 1:
29 print 'usage:\n\tpython cdays-3-exercise-2.py cdays-3-test.txt'
30 else:
31 #调用collect函数,返回结果
32 result = collect(open(sys.argv[1], 'r'))
33 #输出结果
34 for (right, lefts) in result.items():
35 print "%d '%s'\t=>\t%s" % (len(lefts), right, lefts)
- 八皇后问题。在8*8的棋盘上,放置8个皇后,使得任两个皇后不在同行同列同正负对角线上。
1 #coding:utf-8
2 '''cdays-3-exercise-3.py using global varibles, invoke function recursively
3 '''
4 #定义一些全局变量
5 global col
6 global row
7 global pos_diag
8 global nag_diag
9 global count
10
11 def output():
12 ''' function output: print out one state
13 '''
14 global count
15 print row
16 count += 1
17
18 def do_queen(i):
19 ''' function do_queen: generate all states of queens' position
20 @param i: the number of queen
21 '''
22 #依次尝试0~7位置
23 for j in range(0, 8):
24 #若该行,正对角线,负对角线上都没有皇后,则放入i皇后
25 if col[j] == 1 and pos_diag[i-j+7] == 1 and nag_diag[i+j] == 1:
26 row[i] = j
27 #调整各个列表状态
28 col[j] = 0
29 pos_diag[i-j+7] = 0
30 nag_diag[i+j] = 0
31 if i < 7:
32 #可递增或递减
33 do_queen(i+1)
34 else:
35 #产生一个结果,输出
36 output()
37 #恢复各个列表状态为之前的
38 col[j] = 1
39 pos_diag[i-j+7] = 1
40 nag_diag[i+j] = 1
41
42 if __name__ == '__main__':
43 #矩阵列的列表,存储皇后所在列,若该列有皇后,则相应置为1,反之则0
44 col = []
45 #矩阵行的列表,存放每行皇后所在的位置,随着程序的执行,在不断的变化中,之间输出结果
46 row = []
47 #正对角线,i-j恒定,-7~0~7,并且b(i)+7统一到0~14
48 pos_diag = []
49 #负对角线,i+j恒定,0~14
50 nag_diag = []
51 count = 0
52 #一些初始化工作
53 for index in range(0, 8):
54 col.append(1)
55 row.append(0)
56 for index in range(0, 15):
57 pos_diag.append(1)
58 nag_diag.append(1)
59 #开始递归,先放一个,依次递增,反过来,从7开始递减也可
60 do_queen(0)
61 print 'Totally have %d solutions!' % count
1.1.4. CDays-2
把最后探索出的 cdcGrep()嵌入 pycdc-v0.5.py 实现完成版本的 PyCDC
- 编写一个类,实现简单的栈。数据的操作按照先进后出(FILO)的顺序。主要成员函数为put(item),实现数据item插入栈中;get(),实现从栈中取一个数据。
1.1.5. CDays-1
- 自动判定你自个儿的Blog 是什么编码的?
- 在题一基础上,如果blog的编码不是utf-8,编写小程序自动将其转换成utf-8 编码保存到本地?
1.1.6. CDays-0
- 请根据软件发布的流程和软件开发的编码规范,将读者之前章节写的程序修改并发布出去。另外,可以查找下除了epydoc外还有哪些较好的py文档生成器?
1.1.7. CDays+1
- 编程实现以下功能并进行最大化的优化:遍历指定目录下的所有文件,找出其中占用空间最大的前3个文件。
利用ConfigParser,将上述题目中产生的结果按照cdays+1-my.ini格式存储到文件cdays+1-result.txt中。
1.1.8. CDays+2
- 如果在Karrigell 实例中,不复制 cdctools.py 到webapp 目录中,也可以令 index.ks 引用到?
- 经过本章Karrigell的初步学习,实现一个简易的web留言系统。主要利用Karrigell_quick_form实现提交留言并显示出来。
1.1.9. CDays+3
- 熟悉线程相关知识后,利用Lock和RLock实现线程间的简单同步,使得10个线程对同一共享变量进行递增操作,使用加锁机制保证变量结果的正确。
- 使用Queue实现多线程间的同步。比如说,十个输入线程从终端输入字符串,另十个输出线程依次获取字符串并输出到屏幕。
- Python中的Event是用于线程间的相互通信,主要利用信号量机制。修改题一的程序,利用信号量重新实现多线程对同一共享变量进行递增操作。
1.2. KDays
1.3. 小结