可爱的python习题答案_第1页
可爱的python习题答案_第2页
可爱的python习题答案_第3页
可爱的python习题答案_第4页
可爱的python习题答案_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、可爱的 python 习题答案status 校对 lizzie 完成度 100%CDays-51. 计算今年是闰年嘛 ?判断闰年条件 , 满足年份模 400 为 0, 或者模 4 为 0 但模 100 不为 0.o 源代码Toggle line numbers1 #coding:utf-82 cdays-5-exercise-1.py 判断今年是否是闰年3 note: 使用了 import, time 模块 , 逻辑分支 , 字串 格式化等4 56 import time # 导入 time 模块7 thisyear = time.localtime()0# 获取当前年份8 if thisye

2、ar %4 00 = 0 or thisyear %4 =0 and thisyear % 100 0: # 判断闰年条件 , 满足模 400为0, 或者模 4为0但 模 100 不为 09 print this year %s is a leap year % thisyear10 else:11 print this year %si s not a leap year % thisyear12o 运行截屏2. 利用 python 作为科学计算器。熟悉 Python 中的常用运算符,并分别求出表达式 12*34+78-132/6 、(12*(34+78)-132)/6 、(86/40)*5

3、 的值。并利用 math 模块进行 数学计算,分别求出 145/23 的余数, 0.5 的 sin 和 cos 值(注意 sin 和 cos 中参 数是弧度制表示)提醒 : 可通过 import math; help(math) 查看 math 帮助 .o 源代码Toggle line numbers1 #coding:utf-82 cdays-5-exercise-2.py求表达式的值3 note: 基本表达式运算 , 格式化输出 , math 模块4 see: math 模块使用可参考67 x = 12*34+78-132/6 #8 y = (12*(34+78)-132)/69 z =

4、(86/40)*510表达式计算11 print 12*34+78-132/6 = %d % x12 print (12*(34+78)-132)/6 = %d % y13 print (86/40)*5 = %f % z1415 import math #1617 a = math.fmod(145, 23) #18 b = math.sin(0.5) #19 c = math.cos(0.5) #20导入数学计算模块求余函式正弦函式余弦函式21 print 145/23的余数 = %d % a22 print sin(0.5) = %f %b23 print cos(0.5) = %f %

5、c24o 运行截屏3. 找出 0100 之间的所有素数。o 源代码Toggle line numbers1 #coding:utf-82 cdays-5-exercise-3.py求 0100 之间的所有素数3 note: for循环 , 列表类型4 see: math模块使用可参考5 67 from math import sqrt89 N = 10010 # 基本的方法11 result1 = 12 for num in range(2, N):13 f = True14 for snu in range(2, int(sqrt(num)+1):15 if num % snu = 0:16

6、 f = False17 break18 if f:19 result1.append(num)20 print result12122 # 更好的方法23 result2 = p for p in range(2, N) if 0 not in p% d for d in range(2, int(sqrt(p)+1) 24 print result225o 运行截屏CDays-41. os 模块中还有哪些功能可以使用 ? - 提示使用 dir() 和 help()o os 模块中还有很多功能,主要的有以下些:? os.error, os.path, os.popen, os.stat_re

7、sult, os.sys, os.system等等等 ,详细可参见 dir(os) 和 Python 帮助文档 help(os)2. open() 还有哪些模式可以使用 ?o open() 有以下几种模式 :?r: 以只读方式打开已存在文件, 若文件不存在则抛出异常。此方式 是默认方式?U或者 rU: Python 惯例构造了通用换行支持 ;提供U模式以文本方 式打开一个文件 ,但是行可能随时结束 :Unix 的结束符规定为 n, 苹果系统则为 r, 还有 Windows 规定为 rn, 所有这些规定在 Python 程序中统一为 n.?w: 以可写方式打开存在或者不存在的文件,若文件不存在则

8、先新 建该文件,若文件存在则覆盖该文件?a: 用于追加,对 unix 系统而言 ,所有的内容都将追加到文件末尾而 不管指针的当前位置如何?b: 以二进制方式打开。 打开一个二进制文件必须用该模式。 增加 b模式是用来兼容系统对当二进制和文本文件的处理不同? r+,w+ 和a+以更新方式打开文件 (注意 w+覆盖文件 )3. 尝试 for . in . 循环可以对哪些数据类型进行操作 ?o for.in 循环对于任何序列(列表,元组,字符串)都适用。但从广义说来 可以使用任何种类的由任何对象组成的序列4. 格式化声明 ,还有哪些格式可以进行约定 ?o 格式化申明o 详细: ( 精巧地址 : )?

9、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 Flo

10、ating 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 cha

11、racter (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.5. 现在的写入文件模式好嘛 ? 有改进的余地 ?o CDay-4-5.py 好在哪里 ?Toggle line numbers1 # coding : u

12、tf-823 import os45 export = 6 for root, dirs, files in os.walk(/media/cdrom0):7 export+=n %s;%s;%s % (root,dirs,files)8 open(mycd2.cdc, w).write(export)9o CDay-4-6.py 又更加好在哪里Toggle line numbers1 # coding : utf-823 import os45 export = 6 for root, dirs, files in os.walk(/media/cdrom0):7 export.append

13、(n %s;%s;%s % (root,dirs,files)8 open(mycd2.cdc, w).write(.join(export)9o CDay-4-5.py 中使用了字符串的 +连接,而 CDay-4-6.py 中是利用 join 。 字符串的 join 要比 +操作效率高。因为对象的反复 + ,比一次性内建处理, 要浪费更多的资源。6. 读取文件 cdays-4-test.txt 内容,去除空行和注释行后,以行为单位进行排序,并 将结果输出为 cdays-4-result.txt 。o cdays-4-test.txto #some wordsoo Sometimes in l

14、ife,o You find a special friend;o Someone who changes your life just by being part of it.o Someone who makes you laugh until you cant stop;o Someone who makes you believe that there really is good in the world.o Someonew ho convinces you that there really is an unlocked door just waiting for you to

15、open it.o This is Forever Friendship.o when youre down,o and the world seems dark and empty,o Your forever friend lifts you up in spirits and makes that dark and empty worldo suddenly seem bright and full.o Your forever friend gets you through the hard times,thesad times,and the confused times.o If

16、you turn and walk away,o Your forever friend follows,o If you lose you way,o Your forever friend guides you and cheers you on. Your forever friend holds your hand and tells you that everything is going to be okay.o 源代码Toggle line numbers1 #coding:utf-82 cdays-4-exercise-6.py 文件基本操作3 note: 文件读取写入 , 列

17、表排序 , 字符串操作4 see: 字符串各方法可参考 hekp(str) 或 Python 在线 文档5 67 f = open(cdays-4-test.txt, r) #以读方式打开文件8 result = list()9 for line in f.readlines(): #依次读取每行10 line = line.strip() #去掉每行头尾空白11 if not len(line) or line.startswith(#): #判断是否是空行或注释行12 continue #是的话,跳过不处理13 result.append(line)#保存14 result.sort()

18、#排序结果15 print result16 open(cdays-4-result.txt, w).write(%s % n.join(result) # 保存入结果文件17o 运行截屏CDays-31. 根据 DiPy 10.6. 处理命令行参数 ( 精巧地址 :) 使用 getopt.getopt() 优化当前功能函 式。o 源代码Toggle line numbers1 # coding=utf-82 Lovely Python -3 PyDay3 PyCDC v0.34 see :5 6 import os,sys7 import getopt # 导入 getopt 模块89 CD

19、ROM = /media/cdrom010 def cdWalker(cdrom,cdcfile):11 export = 12 for root, dirs, files in os.walk(cdrom):13 export+=n %s;%s;%s % (root,dirs,files)14 open(cdcfile, w).write(export)1516 def usage():17 print PyCDC 使用方式 :18 python cdays-3-exercise-1.py -d cdc -k 中国火19 # 搜索 cdc 目录中的光盘信息,寻找有“中国火”字 样的文件或是目

20、录,在哪张光盘中20 21 try:22 opts, args = getopt.getopt(sys.argv1:,hd:e:k:)23 except getopt.GetoptError:24 usage()25 sys.exit()2627 if len(opts) = 0:28 usage()29 sys.exit()3031 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.argv2 中是否有目录, 以便进行自动

21、创建38 #cdWalker(CDROM, arg)39 print 记录光盘信息到 %s % arg40 elif opt = -d:41 c_path = arg42 elif opt = -k:43 if not c_path:44 usage()45 sys.exit()46 # 进行文件搜索472. 读取某一简单索引文件 cdays-3-test.txt ,其每行格式为文档序号 关键词,现需根 据这些信息转化为倒排索引,即统计关键词在哪些文档中,格式如下:包含该关 键词的文档数 关键词 = 文档序号。其中,原索引文件作为命令行参数传入主 程序,并设计一个 collect 函式统计 关

22、键字 序号 结果对,最后在主程序中 输出结果至屏幕。o cdays-3-test.txt 内容 :o 1 key1o 2 key2o 3 key1o 7 key3o 8 key2o 10 key1o 14 key2o 19 key4o 20 key130 key3o 源代码Toggle line numbers1 #coding:utf-82 cdays-3-exercise-2.py 字典的使用3 not: 使用 sys.args, 字典操作 , 函式调用4 see: sys 模块参见 help(sys)5 67 import sys#导入 sys 模块89 def collect(file

23、):10 改变 key-value 对为 value-key对11param file:文件对象12return:一个 dict 包含 value-key对1314result = 15for linein (): #依次读取每行16left, right =line.split()#将一行以空格分割为左右两部分17 if result.has_key(right): #判断是否已经含有 right 值对应的 key18 resultright.append(left) #若有,直接添加到 resultright 的值列表19 else:20 resultright = left#没有,则新建

24、 resultright 的值列表21 return result2223 if _name_ = _main_:24 if len(sys.argv) = 1: #判断参数个数25 print usage:ntpython cdays-3-exercise-2.py cdays-3-test.txt26 else:27 result = collect(open(sys.argv1, r)#调用 collect 函式,返回结果28 for (right, lefts) in result.items(): #输出结果29 print %d %st=t%s % (len(lefts),righ

25、t, lefts)30o 运行截屏3. 八皇后问题。在 8*8 的棋盘上,放置 8 个皇后,使得任两个皇后不在同行同列同 正负对角线上。o 源代码Toggle line numbers1 #coding:utf-82 cdays-3-exercise-3.py3 note: 使用全局变量和函式的递归调用4 56 global col # 定义一 些全局变量7 global row8 global pos_diag9 global nag_diag10 global count1112 def output():13 输出一种有效结果1415global count16print row17co

26、unt += 11819 def do_queen(i):20 生成所有正确解21param i: 皇后的数目2223 for j in range(0, 8):#试 0 7 位置依次尝24 if colj = 1 and pos_diagi-j+7 = 1 andnag_diagi+j = 1: #若该行,正对角线,负对角线上都没有 皇后,则放入 i 皇后25 rowi = j26 colj = 0 #个列表状态27 pos_diagi-j+7 = 028 nag_diagi+j = 029 if i 14ro = PyCDC0.5 使用说明 :15dir目录名#指定保存和搜

27、索目录,默认是cdc16walk文件名#指定光盘信息文件名,使用*.cdc17find关键词#遍历搜索目录中所有.cdc 文件,输#出含有关键词的行18 ? #19 EOF #Crtl+D(Unix)|Ctrl+Z(Dos/Windows)20 查询退出系统,也可以使用2122 def help_EOF(self):23 print 退出程序 Quits the program24 def do_EOF(self, line):25 sys.exit()2627 def help_walk(self):28 print 扫描光盘内容 walk cd and export into*.cdc29

28、 def do_walk(self, ):30 if = : = raw_input(输入 cdc 文件名 : )31 print 扫描光盘内容保存到 :%s %32 cdWalker(self.CDROM,self.CDDIR+)3334 def help_dir(self):35print 指定保存 / 搜索目录 36 def do_dir(self, pathname):37 if pathname = : pathname = raw_input(输入指定保存 / 搜索目录 : )38 self.CDDIR = pathname39 print 指定保存 / 搜索目录 :%s ; 默认

29、是:%s % (pathname,self.CDDIR)4041 def help_find(self):42 print 搜索关键词 43 def do_find(self, keyword):44 if keyword = : keyword = raw_input(输入搜索关键字 : )45print 搜索关键词 :%s % keyword46cdcGrep(self.CDDIR,keyword)4748 if_name_= _main_: #this way the modulecan be49 cdc = PyCDC() # imported by other programs as

30、 well50 cdc.cmdloop()512. 编写一个类,实现简单的栈。数据的操作按照先进后出 (FILO) 的顺序。主要成员函 式为 put(item) ,实现数据 item 插入栈中; get() ,实现从栈中取一个数据。o 源代码Toggle line numbers1 #coding:utf-82 cdays-2-exercise-2.py自定义栈3 note: 类和对象的使用4 56 class MyStack(object):7 MyStack8 自定义栈,主要操作有 put(), get() andisEmpty()9 10def _init_(self, max):111

31、2初始栈头指针和清空栈13param max: 指定栈的最大长度1415self.head = -116self.stack = list()17self.max = max18for i in range(self.max):19self.stack.append(0)2021def put(self, item):2223将 item 压入栈中24param item: 所要入栈的项2526if self.head = self.max:#判断当前栈是否满了27return Put Error: The Stack isOverflow! # 提示栈溢出28else:29self.head

32、 += 1#不满,则将 item 入栈,调整栈顶指针30self.stackself.head = item31print Put %s Success % item3233def get(self):3435获得当前栈顶 item36return: 栈顶 item3738if self.head 0:#判断当前栈是否为空39return Get Error: The Stack is Empty!#提示栈空40 else:41 self.head -= 1#出栈,返回栈顶元素,并调整栈顶指针42 return self.stackself.head+14344 def isEmpty(sel

33、f):45 46 获得当前栈的状态,空或者非空47 return: True(栈空 ) or False( 栈非空 )48 49 if self.head -1:50 return True51 return False5253 if _name_ = _main_:54 mystack = MyStack(100)55 mystack.put(a)56 mystack.put(b)57 print mystack.get()58 mystack.put(c)59 print mystack.get()60 print mystack.get()61 print mystack.get()62

34、o 运行截屏CDays-11. 自动判定你自个儿或是朋友的 Blog 是什么编码的 ?o 源代码Toggle line numbers1 #coding:utf-82 cdays-1-exercise-1.py3 author: Ushengyan4 version:$Id$5 note: 使用 chardet 和 urllib26 see: chardet使用文档 : , urllib2 使用参考 : 89 import sys10 import urllib211 import chardet1213 def blog_detect(blogurl):14 15检测 blog 的编码方式1

35、6param blogurl: 要检测 blog 的 url1718try:19fp = urllib2.urlopen(blogurl)#尝试打开给定 url20except Exception, e:#若产生异常,则给出相关提示并返回21print e22print download exception %s % blogurl23return 024blog = fp.read()#读取内容25codedetect = chardet.detect(blog)encoding#检测得到编码方式26print %st-t%s % (blogurl, codedetect)27fp.clos

36、e()#关闭28return 12930 if_name_ = _main_:31if len(sys.argv) = 1:32print usage:ntpythoncdays1-exercise-1.py 33else:34blog_detect(sys.argv1)352. 如果是 o运行截屏utf-8 的 ,编写小程序自动将指定文章转换成utf-8 编码保存 ?源代码Toggle line numbers1 #coding:utf-82 cdays-1-exercise-2.py熟悉 chardet 和 urllib23 author: Ushengyan4 version:$Id$5

37、 note: 使用 chardet 和 urllib26 see: chardet使用文档 : , urllib2使用参考 :8 import sys9 import urllib210 import chardet1112 def blog_detect(blogurl):13 14 检测 blog 的编码方式15 param blogurl: 要检测 blog 的 url16 17 try:18 fp = urllib2.urlopen(blogurl)#尝试打开给定 url19 except Exception, e: #若产生异常,则给出相关提示并返回print eprint down

38、load exception %s % blogurl return 0blog = fp.read()20212223 #读取内容24 fp.close()#关闭25 codedetect = chardet.detect(blog)encoding #检测得到编码方式26 if codedetect utf-8: #是否是 utf-827 try:#print blogblog = blog.encode(utf-8) except:print ubad unicode encode try! return 0= %s_utf-8 % blogurl7:28 blog = unicode(

39、blog, codedetect) #不是的话,则尝试转换293031323334#保存入文件353637383940 if41 if len(sys.argv)42 cdays-1-exercise-2.py 43 else:44 blog_detect(sys.argv1)45= (/, _)open(, w).write(%s % blog) print save to %return 1_main_: = 1: print usage:ntpythonnameo 运行截屏CDays01. 请根据软件发布的流程和软件开发的编码规范, 将读者之前章节写的程序修改并发 布出去。另外,可以查找

40、下除了 epydoc 外还有哪些较好的 py 文档生成器? o 步骤:? 编写 epydoc 的配置文件如 cdays0-epydoc.cfg 。?epydoc?# Epydoc section marker (required byConfigParser)? # Information about the project.?name: MyStack?url:# The list of modules to document. Modules can be named using# dotted names, module , or package directory names.# Th

41、is option may be repeated.modules: ./cdays0-exercise-1.py # Write html output to the directory apidocs output: html target: apidocs/# Include all automatically generated graphs. These graphs are# generated using Graphviz dot.graph: alldotpath: /usr/bin/dot? 在终端中输入 epydoc -config cdays0-epydoc.cfg ,即

42、可生成文档。 o 运行截屏CDays11. 编程实现以下功能并进行最大化的优化: 遍历指定目录下的所有文件, 找出其中占 用空间最大的前 3 个文件。o 源代码Toggle line numbers1 #coding:utf-82 cdays+1-exercise-1.py3 note: 使用 os.stat 获取相关信息 , os.walk 遍历 ,4 see: help(os)5 author: Ushengyan6 version: $Id$7 8 import sys9 import os1011 def get_top_three(path):1213141516 获取给定路径中文件

43、大小最大的三个 param path: 指定路径 return 返回一个 list ,每项为 (size, )all_file = 17 for root, dirs, files in os.walk(path): #遍历 path18 for one files:19 fname = os.path.join(root, onefile)#获得当前处理文件的完整名字20 fsize = os.stat(fname).st_size按照保存#获得当前处理文件大小21 if all_(fsize):#文件大小存储22 all_.append(fname)23 else:24 all_ = fn

44、ame25 fsize_key = all_()#到所有的文件大小26 fsize_key.sort()#排序,从小到大27 result = 28 for i in -1, -2, -3: #依次取最大的三个29 for j in all_i:#30 result.append(fsize_keyi, j)31 return result:3 #返回前三个3233 if _name_ = _main_34 if len(sys.argv) = 1:35 print usage:ntpythoncdays+1-exercise-1.py path36 else:37 abs_path = os

45、.path.abspath(sys.argv1) #得到绝对路径38 if not os.path.isdir(abs_path):#判断所给的路径是否存在39 print %s is not exist % abs_path40 else:41 top = get_top_three(abs_path)42 for (s, f) in top:43 print %st-t%s % (f, s)44o 运行截屏2. 利用 ConfigParser ,将上述题目中产生的结果按照 cdays+1-my.ini 格式存储到文 件 cdays+1-result.txt 中。o cdays+1-my.i

46、ni 内容为:o Numbero = some= someo 源代码Toggle line numbers1 #coding:utf-82 cdays+1-exercise-2.py3 note: 利用 ConfigParser 解析 ini 格式4 see: 文档参见 2.4.1/ConfigParser.html, 其他例 子5 author: Ushengyan6 version:$Id$7 8 import os9 import sys10 from ConfigParser import RawConfigParser1112 def iniTT(size_file):13 按照 .ini 的格式,存储 size_file14 15 cfg = RawConfigParser()16 print size_file17 index = 118 for (s, f) i

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论