status

校对

ShengYan

完成度70%

TableOfContents

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

   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 #coding:utf-8
   2 '''cdays-5-exercise-3.py print out and for expression
   3 '''
   4 for index in range(1, 6):
   5         if index > 3:
   6                 #调整index
   7                 index = 2*3 -index
   8         #输出每行空格个数
   9         print ' '*(3-index),
  10         #输出每行*的个数
  11         print '*'*(2*index - 1)

截图

1.1.2. CDays-4

CDay-4-5.py 好在哪里? :

   1 # coding : utf-8
   2 import os
   3 export = ""
   4 for root, dirs, files in os.walk('/media/cdrom0'):
   5   export+="\n %s;%s;%s" % (root,dirs,files)
   6 open('mycd2.cdc', 'w').write(export)

CDay-4-6.py 又更加好在哪里? :

   1 # coding : utf-8
   2 import os
   3 export = []
   4 for root, dirs, files in os.walk('/media/cdrom0'):
   5     export.append("\n %s;%s;%s" % (root,dirs,files))
   6 open('mycd2.cdc', 'w').write(''.join(export))
  1. CDay-4-5.py中使用了字符串的+连接,而CDay-4-6.py中是利用join。字符串的join要比'+'操作效率高。因为对象的反复+,比一次性内建处理,要浪费更多的资源。

   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

   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                 #进行文件搜索

   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)

   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

   1 

   1 

1.1.5. CDays-1

   1 

   1 

1.1.6. CDays-0

1.1.7. CDays+1

   1 

   1 

1.1.8. CDays+2

   1 

1.1.9. CDays+3

   1 

   1 

   1 

1.2. KDays

1.3. 小结