Differences between revisions 8 and 33 (spanning 25 versions)
Revision 8 as of 2008-04-27 01:02:11
Size: 12990
Editor: lizzie
Comment:
Revision 33 as of 2008-08-28 13:57:04
Size: 812
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
## page was renamed from ObpLovelyPython/LpyAttach-answer
## page was renamed from ObpLovelyPython/Answer
Line 4: Line 6:
||'''status''' || 校对 || ShengYan || 完成度70% ||
[[TableOfContents]]
||'''status''' || 校对 || lizzie || 完成度100% ||
[[TableOfContents(2)]]
Line 7: Line 9:
## 编辑正文收集在:
### http://openbookproject.googlecode.com/svn/trunk/LovelyPython/exercise/part2-KDays/LpyAttach3answer-KDays.moin
### http://openbookproject.googlecode.com/svn/trunk/LovelyPython/exercise/part1-CDays/LpyAttach3answer-CDays.moin

##startInc
Line 8: Line 15:
== CDays ==
=== CDays-5 ===
 * 计算今年是闰年嘛?
  . 相关代码:
{{{
#!python
#coding:utf-8
'''cdays-5-exercise-1.py this year is a leap year or not
'''
#导入time模块
import time
#获取当前年份
thisyear = time.localtime()[0]
#判断闰年条件,满足模400为0,或者模4为0但模100不为0
if thisyear % 400 == 0 or thisyear % 4 ==0 and thisyear % 100 <> 0:
        print 'this year %s is a leap year' % thisyear
else:
        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)。
  . 相关代码:
{{{
#!python
#coding:utf-8
'''cdays-5-exercise-2.py basic operation and math library
'''
#表达式计算
x = 12*34+78-132/6
y = (12*(34+78)-132)/6
z = (8.6/4)**5
print '12*34+78-132/6 = %d' % x
print '(12*(34+78)-132)/6 = %d' % y
print '(8.6/4)**5 = %f' % z
#导入数学计算模块
import math
#求余函数
a = math.fmod(145, 23)
#正弦函数
b = math.sin(0.5)
#余弦函数
c = math.cos(0.5)
print '145/23的余数 = %d' % a
print 'sin(0.5) = %f' %b
print 'cos(0.5) = %f' %c
}}}
 * 编写程序,在屏幕上打印出如下图案:
attachment:cdays-5-exercise-3.png
Line 56: Line 16:
 . 相关代码:
{{{
#!python
#coding:utf-8
'''cdays-5-exercise-3.py print out and for expression
'''
for index in range(1, 6):
        if index > 3:
                #调整index
                index = 2*3 -index
        #输出每行空格个数
        print ' '*(3-index),
        #输出每行*的个数
        print '*'*(2*index - 1)
}}}
截图
== CDays 故事解答 ==
[[Include(/CDays,,from="^##startInc",to="^##endInc")]]
Line 73: Line 19:
=== CDays-4 ===
 * os 模块中还有哪些功能可以使用? -- 提示使用 `dir()` `help()`
  1. os.error, os.path, os.popen, os.stat_result, os.sys, os.system等等等
  1. 详细可参见`dir(os)`和python帮助文档`help(os)`
 * `open()` 还有哪些模式可以使用?
  1. 'r': 以只读方式打开已存在文件,若文件不存在则抛出异常。此方式是默认方式
  1. 'U'或者'rU': python惯例构造了通用换行支持;提供'U'模式以文本方式打开一个文件,但是行可能随时结束:Unix的结束符规定为'\n',苹果系统则为'\r',还有windows规定为'\r\n',所有这些规定在python程序中统一为'\n'.如果python不构造一个通用换行支持模式'u'来用统一对待正常文本模式的话
  1. 'w': 以可写方式打开存在或者不存在的文件,若文件不存在则先新建该文件,若文件存在则覆盖该文件
  1. 'a': 用于追加,对unix系统而言,所有的内容都将追加到文件末尾而不管指针的当前位置如何
  1. 'b': 以二进制方式打开。打开一个二进制文件必须用该模式。增加'b'模式是用来兼容系统对当二进制和文本文件的处理不同
  1. 'r+','w+'和'a+'以更新方式打开文件(注意'w+'覆盖文件)
 * 尝试`for .. in ..` 循环可以对哪些数据类型进行操作?
  1. for..in循环对于任何序列(列表,元组,字符串)都适用。但从广义说来可以使用任何种类的由任何对象组成的序列
 * 格式化声明,还有哪些格式可以进行约定?
  详细参考:[http://docs.python.org/lib/typesseq-strings.html typesseq-strings]
  1. d Signed integer decimal.
  1. i Signed integer decimal.
  1. o Unsigned octal.
  1. u Unsigned decimal.
  1. x Unsigned hexadecimal (lowercase).
  1. X Unsigned hexadecimal (uppercase).
  1. e Floating point exponential format (lowercase).
  1. E Floating point exponential format (uppercase).
  1. f Floating point decimal format.
  1. F Floating point decimal format.
  1. g Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise.
  1. G Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise.
  1. c Single character (accepts integer or single character string).
  1. r String (converts any python object using repr()).
  1. s String (converts any python object using str()).
  1. % No argument is converted, results in a "%" character in the result.
== KDays 故事解答 ==
[[Include(/KDays,,from="^##startInc",to="^##endInc")]]
Line 105: Line 22:
 * 现在的写入文件模式好嘛? 有改进的余地?
'''CDay-4-5.py''' 好在哪里? :

{{{
#!python
# coding : utf-8
import os
export = ""
for root, dirs, files in os.walk('/media/cdrom0'):
  export+="\n %s;%s;%s" % (root,dirs,files)
open('mycd2.cdc', 'w').write(export)
}}}
'''CDay-4-6.py''' 又更加好在哪里? :

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

 * 读取文件cdays-4-test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为cdays-4-result.txt。
{{{
#!python
#coding:utf-8
'''cdays-4-exercise-6.py file operation
'''
#以读方式打开文件
f = open('cdays-4-test.txt', 'r')
result = list()
#依次读取每行
for line in f.readlines():
        #去掉每行头尾空白
 line = line.strip()
        #判断是否是空行或注释行
 if not len(line) or line.startswith('#'):
                #是的话,跳过不处理
  continue
 result.append(line)
#排序结果
result.sort()
#保存入结果文件
open('cdays-4-result.txt', 'w').write('%s' % '\n'.join(result))
}}}
=== CDays-3 ===
 * 根据 [http://www.woodpecker.org.cn/diveintopython/scripts_and_streams/command_line_arguments.html DiPy 10.6. 处理命令行参数] 使用`getopt.getopt()` 优化当前功能函式。
{{{
#!python
# coding=utf-8
'''Lovely Python -3 PyDay
    PyCDC v0.3
'''
import os,sys
import getopt

CDROM = '/media/cdrom0'
def cdWalker(cdrom,cdcfile):
 export = ""
 for root, dirs, files in os.walk(cdrom):
  export+="\n %s;%s;%s" % (root,dirs,files)
 open(cdcfile, 'w').write(export)

def usage():
 print '''PyCDC 使用方式:
 python cdays-3-exercise-1.py -d cdc -k 中国火
 #搜索 cdc 目录中的光盘信息,寻找有“中国火”字样的文件或是目录,在哪张光盘中
        '''

try:
 opts, args = getopt.getopt(sys.argv[1:], 'hd:e:k:')
except getopt.GetoptError:
 usage()
 sys.exit()

if len(opts) == 0:
 usage()
 sys.exit()

c_path = ''
for opt, arg in opts:
 if opt in ('-h', '--help'):
  usage()
  sys.exit()
 elif opt == '-e':
  #判别sys.argv[2]中是否有目录,以便进行自动创建
  #cdWalker(CDROM, arg)
  print "记录光盘信息到 %s" % arg
 elif opt == '-d':
  c_path = arg
 elif opt == '-k':
  if not c_path:
   usage()
   sys.exit()
  #进行文件搜索

}}}
 * 读取某一简单索引文件cdays-3-test.txt,其每行格式为文档序号 关键词,现需根据这些信息转化为倒排索引,即统计关键词在哪些文档中,格式如下:包含该关键词的文档数 关键词 => 文档序号。其中,原索引文件作为命令行参数传入主程序,并设计一个collect函数统计关键字-序号结果对,最后在主程序中输出结果至屏幕。
{{{
#!python
#coding:utf-8
'''cdays-3-exercise-2.py using sys.args, dict and function invoke
'''
#导入sys模块
import sys

def collect(file):
 ''' function collect: change the key-value to value-key
 @param file: file object
 @return: a dict type, get the value-key pairs
 '''
 result = {}
        #依次读取每行
 for line in file.readlines():
  #将一行以空格分割为左右两部分
  left, right = line.split()#
  #判断是否已经含有right值对应的key
  if result.has_key(right):
   #若有,直接添加到result[right]的值列表
   result[right].append(left)
  else:
                        #没有,则新建result[right]的值列表
   result[right] = [left]
 return result

if __name__ == "__main__":
        #判断参数个数
 if len(sys.argv) == 1:
  print 'usage:\n\tpython cdays-3-exercise-2.py cdays-3-test.txt'
 else:
                #调用collect函数,返回结果
  result = collect(open(sys.argv[1], 'r'))
                #输出结果
  for (right, lefts) in result.items():
   print "%d '%s'\t=>\t%s" % (len(lefts), right, lefts)
}}}
 * 八皇后问题。在8*8的棋盘上,放置8个皇后,使得任两个皇后不在同行同列同正负对角线上。
{{{
#!python
#coding:utf-8
'''cdays-3-exercise-3.py using global varibles, invoke function recursively
'''
#定义一些全局变量
global col
global row
global pos_diag
global nag_diag
global count

def output():
 ''' function output: print out one state
 '''
 global count
 print row
 count += 1

def do_queen(i):
 ''' function do_queen: generate all states of queens' position
 @param i: the number of queen
 '''
        #依次尝试0~7位置
 for j in range(0, 8):
  #若该行,正对角线,负对角线上都没有皇后,则放入i皇后
  if col[j] == 1 and pos_diag[i-j+7] == 1 and nag_diag[i+j] == 1:
   row[i] = j
   #调整各个列表状态
   col[j] = 0
   pos_diag[i-j+7] = 0
   nag_diag[i+j] = 0
   if i < 7:
    #可递增或递减
    do_queen(i+1)
   else:
    #产生一个结果,输出
    output()
   #恢复各个列表状态为之前的
   col[j] = 1
   pos_diag[i-j+7] = 1
   nag_diag[i+j] = 1

if __name__ == '__main__':
 #矩阵列的列表,存储皇后所在列,若该列有皇后,则相应置为1,反之则0
 col = []
 #矩阵行的列表,存放每行皇后所在的位置,随着程序的执行,在不断的变化中,之间输出结果
 row = []
 #正对角线,i-j恒定,-7~0~7,并且b(i)+7统一到0~14
 pos_diag = []
 #负对角线,i+j恒定,0~14
 nag_diag = []
 count = 0
        #一些初始化工作
 for index in range(0, 8):
  col.append(1)
  row.append(0)
 for index in range(0, 15):
  pos_diag.append(1)
  nag_diag.append(1)
        #开始递归,先放一个,依次递增,反过来,从7开始递减也可
 do_queen(0)
 print 'Totally have %d solutions!' % count

}}}
=== CDays-2 ===
 * 把最后探索出的 `cdcGrep()`嵌入 pycdc-v0.5.py 实现完成版本的 PyCDC
{{{
#!python

}}}
 * 编写一个类,实现简单的栈。数据的操作按照先进后出(FILO)的顺序。主要成员函数为put(item),实现数据item插入栈中;get(),实现从栈中取一个数据。
{{{
#!python

}}}
=== CDays-1 ===
 * 自动判定你自个儿的Blog 是什么编码的?
{{{
#!python

}}}
 * 在题一基础上,如果blog的编码不是utf-8,编写小程序自动将其转换成utf-8 编码保存到本地?
{{{
#!python

}}}
=== CDays-0 ===
 * 请根据软件发布的流程和软件开发的编码规范,将读者之前章节写的程序修改并发布出去。另外,可以查找下除了epydoc外还有哪些较好的py文档生成器?
=== CDays+1 ===
 * 编程实现以下功能并进行最大化的优化:遍历指定目录下的所有文件,找出其中占用空间最大的前3个文件。
{{{
#!python

}}}
 * 利用ConfigParser,将上述题目中产生的结果按照cdays+1-my.ini格式存储到文件cdays+1-result.txt中。
{{{
#!python

}}}
=== CDays+2 ===
 * 如果在Karrigell 实例中,不复制 cdctools.py 到webapp 目录中,也可以令 index.ks 引用到?
 * 经过本章Karrigell的初步学习,实现一个简易的web留言系统。主要利用Karrigell_quick_form实现提交留言并显示出来。
{{{
#!python

}}}
=== CDays+3 ===
 * 熟悉线程相关知识后,利用Lock和RLock实现线程间的简单同步,使得10个线程对同一共享变量进行递增操作,使用加锁机制保证变量结果的正确。
{{{
#!python

}}}
 * 使用Queue实现多线程间的同步。比如说,十个输入线程从终端输入字符串,另十个输出线程依次获取字符串并输出到屏幕。
{{{
#!python

}}}
 * Python中的Event是用于线程间的相互通信,主要利用信号量机制。修改题一的程序,利用信号量重新实现多线程对同一共享变量进行递增操作。
{{{
#!python

}}}
== KDays ==
== 小结 ==
## 总体语法等等叙述,注意给出相关知识的阅读指导
##endInc

status

校对

lizzie

完成度100%

TableOfContents(2)

1. 故事练习解答

1.1. CDays 故事解答

Include(/CDays,,from="^##startInc",to="^##endInc")

1.2. KDays 故事解答

Include(/KDays,,from="^##startInc",to="^##endInc")


ObpLovelyPython/LpyAttach3answer (last edited 2009-12-25 07:14:24 by localhost)