可爱的python习题答案.docx
- 文档编号:27363978
- 上传时间:2023-06-29
- 格式:DOCX
- 页数:49
- 大小:758.22KB
可爱的python习题答案.docx
《可爱的python习题答案.docx》由会员分享,可在线阅读,更多相关《可爱的python习题答案.docx(49页珍藏版)》请在冰豆网上搜索。
可爱的python习题答案
可爱的python习题答案
status
校对
lizzie
完成度100%
CDays-5
1.计算今年是闰年嘛?
判断闰年条件,满足年份模400为0,或者模4为0但模100不为0.
o源代码
Togglelinenumbers
1#coding:
utf-8
2'''cdays-5-exercise-1.py判断今年是否是闰年
3@note:
使用了import,time模块,逻辑分支,字串格式化等
4'''
5
6importtime#导入time模块
7thisyear=time.localtime()[0]#获取当前年份
8ifthisyear%400==0orthisyear%4==0andthisyear%100<>0:
#判断闰年条件,满足模400为0,或者模4为0但模100不为0
9print'thisyear%sisaleapyear'%thisyear
10else:
11print'thisyear%sisnotaleapyear'%thisyear
12
o运行截屏
2.利用python作为科学计算器。
熟悉Python中的常用运算符,并分别求出表达式12*34+78-132/6、(12*(34+78)-132)/6、(86/40)**5的值。
并利用math模块进行数学计算,分别求出145/23的余数,0.5的sin和cos值(注意sin和cos中参数是弧度制表示)提醒:
可通过importmath;help("math")查看math帮助.
o源代码
Togglelinenumbers
1#coding:
utf-8
2'''cdays-5-exercise-2.py求表达式的值
3@note:
基本表达式运算,格式化输出,math模块
4@see:
math模块使用可参考http:
//docs.python.org/lib/module-math.html
5'''
6
7x=12*34+78-132/6#表达式计算
8y=(12*(34+78)-132)/6
9z=(86/40)**5
10
11print'12*34+78-132/6=%d'%x
12print'(12*(34+78)-132)/6=%d'%y
13print'(86/40)**5=%f'%z
14
15importmath#导入数学计算模块
16
17a=math.fmod(145,23)#求余函式
18b=math.sin(0.5)#正弦函式
19c=math.cos(0.5)#余弦函式
20
21print'145/23的余数=%d'%a
22print'sin(0.5)=%f'%b
23print'cos(0.5)=%f'%c
24
o运行截屏
3.找出0~100之间的所有素数。
o源代码
Togglelinenumbers
1#coding:
utf-8
2'''cdays-5-exercise-3.py求0~100之间的所有素数
3@note:
for循环,列表类型
4@see:
math模块使用可参考http:
//docs.python.org/lib/module-math.html
5'''
6
7frommathimportsqrt
8
9N=100
10#基本的方法
11result1=[]
12fornuminrange(2,N):
13f=True
14forsnuinrange(2,int(sqrt(num))+1):
15ifnum%snu==0:
16f=False
17break
18iff:
19result1.append(num)
20printresult1
21
22#更好的方法
23result2=[pforpinrange(2,N)if0notin[p%dfordinrange(2,int(sqrt(p))+1)]]
24printresult2
25
o运行截屏
CDays-4
1.os模块中还有哪些功能可以使用?
--提示使用dir()和help()
oos模块中还有很多功能,主要的有以下些:
▪os.error,os.path,os.popen,os.stat_result,os.sys,os.system等等等,详细可参见dir("os")和Python帮助文档help("os")
2.open()还有哪些模式可以使用?
oopen()有以下几种模式:
▪'r':
以只读方式打开已存在文件,若文件不存在则抛出异常。
此方式是默认方式
▪'U'或者'rU':
Python惯例构造了通用换行支持;提供'U'模式以文本方式打开一个文件,但是行可能随时结束:
Unix的结束符规定为'\n',苹果系统则为'\r',还有Windows规定为'\r\n',所有这些规定在Python程序中统一为'\n'.
▪'w':
以可写方式打开存在或者不存在的文件,若文件不存在则先新建该文件,若文件存在则覆盖该文件
▪'a':
用于追加,对unix系统而言,所有的内容都将追加到文件末尾而不管指针的当前位置如何
▪'b':
以二进制方式打开。
打开一个二进制文件必须用该模式。
增加'b'模式是用来兼容系统对当二进制和文本文件的处理不同
▪'r+','w+'和'a+'以更新方式打开文件(注意'w+'覆盖文件)
3.尝试for..in..循环可以对哪些数据类型进行操作?
ofor..in循环对于任何序列(列表,元组,字符串)都适用。
但从广义说来可以使用任何种类的由任何对象组成的序列
4.格式化声明,还有哪些格式可以进行约定?
o格式化申明
o详细:
http:
//docs.python.org/lib/typesseq-strings.html(精巧地址:
http:
//bit.ly/2TH7cF)
▪dSignedintegerdecimal.
▪iSignedintegerdecimal.
▪oUnsignedoctal.
▪uUnsigneddecimal.
▪xUnsignedhexadecimal(lowercase).
▪XUnsignedhexadecimal(uppercase).
▪eFloatingpointexponentialformat(lowercase).
▪EFloatingpointexponentialformat(uppercase).
▪fFloatingpointdecimalformat.
▪FFloatingpointdecimalformat.
▪gFloatingpointformat.Usesexponentialformatifexponentisgreaterthan-4orlessthanprecision,decimalformatotherwise.
▪GFloatingpointformat.Usesexponentialformatifexponentisgreaterthan-4orlessthanprecision,decimalformatotherwise.
▪cSinglecharacter(acceptsintegerorsinglecharacterstring).
▪rString(convertsanypythonobjectusingrepr()).
▪sString(convertsanypythonobjectusingstr()).
▪%Noargumentisconverted,resultsina"%"characterintheresult.
5.现在的写入文件模式好嘛?
有改进的余地?
oCDay-4-5.py好在哪里?
Togglelinenumbers
1#coding:
utf-8
2
3importos
4
5export=""
6forroot,dirs,filesinos.walk('/media/cdrom0'):
7export+="\n%s;%s;%s"%(root,dirs,files)
8open('mycd2.cdc','w').write(export)
9
oCDay-4-6.py又更加好在哪里?
Togglelinenumbers
1#coding:
utf-8
2
3importos
4
5export=[]
6forroot,dirs,filesinos.walk('/media/cdrom0'):
7export.append("\n%s;%s;%s"%(root,dirs,files))
8open('mycd2.cdc','w').write(''.join(export))
9
oCDay-4-5.py中使用了字符串的+连接,而CDay-4-6.py中是利用join。
字符串的join要比+操作效率高。
因为对象的反复+,比一次性内建处理,要浪费更多的资源。
6.读取文件cdays-4-test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为cdays-4-result.txt。
ocdays-4-test.txt
o#somewords
o
oSometimesinlife,
oYoufindaspecialfriend;
oSomeonewhochangesyourlifejustbybeingpartofit.
oSomeonewhomakesyoulaughuntilyoucan'tstop;
oSomeonewhomakesyoubelievethattherereallyisgoodintheworld.
oSomeonewhoconvincesyouthattherereallyisanunlockeddoorjustwaitingforyoutoopenit.
oThisisForeverFriendship.
owhenyou'redown,
oandtheworldseemsdarkandempty,
oYourforeverfriendliftsyouupinspiritsandmakesthatdarkandemptyworld
osuddenlyseembrightandfull.
oYourforeverfriendgetsyouthroughthehardtimes,thesadtimes,andtheconfusedtimes.
oIfyouturnandwalkaway,
oYourforeverfriendfollows,
oIfyouloseyouway,
oYourforeverfriendguidesyouandcheersyouon.
Yourforeverfriendholdsyourhandandtellsyouthateverythingisgoingtobeokay.
o源代码
Togglelinenumbers
1#coding:
utf-8
2'''cdays-4-exercise-6.py文件基本操作
3@note:
文件读取写入,列表排序,字符串操作
4@see:
字符串各方法可参考hekp(str)或Python在线文档http:
//docs.python.org/lib/string-methods.html
5'''
6
7f=open('cdays-4-test.txt','r')#以读方式打开文件
8result=list()
9forlineinf.readlines():
#依次读取每行
10line=line.strip()#去掉每行头尾空白
11ifnotlen(line)orline.startswith('#'):
#判断是否是空行或注释行
12continue#是的话,跳过不处理
13result.append(line)#保存
14result.sort()#排序结果
15printresult
16open('cdays-4-result.txt','w').write('%s'%'\n'.join(result))#保存入结果文件
17
o运行截屏
CDays-3
1.根据DiPy10.6.处理命令行参数(精巧地址:
http:
//bit.ly/1x5gMw)使用getopt.getopt()优化当前功能函式。
o源代码
Togglelinenumbers
1#coding=utf-8
2'''LovelyPython-3PyDay
3PyCDCv0.3
4@see:
5'''
6importos,sys
7importgetopt#导入getopt模块
8
9CDROM='/media/cdrom0'
10defcdWalker(cdrom,cdcfile):
11export=""
12forroot,dirs,filesinos.walk(cdrom):
13export+="\n%s;%s;%s"%(root,dirs,files)
14open(cdcfile,'w').write(export)
15
16defusage():
17print'''PyCDC使用方式:
18pythoncdays-3-exercise-1.py-dcdc-k中国火
19#搜索cdc目录中的光盘信息,寻找有“中国火”字样的文件或是目录,在哪张光盘中
20'''
21try:
22opts,args=getopt.getopt(sys.argv[1:
],'hd:
e:
k:
')
23exceptgetopt.GetoptError:
24usage()
25sys.exit()
26
27iflen(opts)==0:
28usage()
29sys.exit()
30
31c_path=''
32foropt,arginopts:
33ifoptin('-h','--help'):
34usage()
35sys.exit()
36elifopt=='-e':
37#判别sys.argv[2]中是否有目录,以便进行自动创建
38#cdWalker(CDROM,arg)
39print"记录光盘信息到%s"%arg
40elifopt=='-d':
41c_path=arg
42elifopt=='-k':
43ifnotc_path:
44usage()
45sys.exit()
46#进行文件搜索
47
2.读取某一简单索引文件cdays-3-test.txt,其每行格式为文档序号关键词,现需根据这些信息转化为倒排索引,即统计关键词在哪些文档中,格式如下:
包含该关键词的文档数关键词=>文档序号。
其中,原索引文件作为命令行参数传入主程序,并设计一个collect函式统计"关键字<->序号"结果对,最后在主程序中输出结果至屏幕。
ocdays-3-test.txt内容:
o1key1
o2key2
o3key1
o7key3
o8key2
o10key1
o14key2
o19key4
o20key1
30key3
o源代码
Togglelinenumbers
1#coding:
utf-8
2'''cdays-3-exercise-2.py字典的使用
3@not:
使用sys.args,字典操作,函式调用
4@see:
sys模块参见help(sys)
5'''
6
7importsys#导入sys模块
8
9defcollect(file):
10'''改变key-value对为value-key对
11@paramfile:
文件对象
12@return:
一个dict包含value-key对
13'''
14result={}
15forlineinfile.readlines():
#依次读取每行
16left,right=line.split()#将一行以空格分割为左右两部分
17ifresult.has_key(right):
#判断是否已经含有right值对应的key
18result[right].append(left)#若有,直接添加到result[right]的值列表
19else:
20result[right]=[left]#没有,则新建result[right]的值列表
21returnresult
22
23if__name__=="__main__":
24iflen(sys.argv)==1:
#判断参数个数
25print'usage:
\n\tpythoncdays-3-exercise-2.pycdays-3-test.txt'
26else:
27result=collect(open(sys.argv[1],'r'))#调用collect函式,返回结果
28for(right,lefts)inresult.items():
#输出结果
29print"%d'%s'\t=>\t%s"%(len(lefts),right,lefts)
30
o运行截屏
3.八皇后问题。
在8*8的棋盘上,放置8个皇后,使得任两个皇后不在同行同列同正负对角线上。
o源代码
Togglelinenumbers
1#coding:
utf-8
2'''cdays-3-exercise-3.py
3@note:
使用全局变量和函式的递归调用
4'''
5
6globalcol#定义一些全局变量
7globalrow
8globalpos_diag
9globalnag_diag
10globalcount
11
12defoutput():
13'''输出一种有效结果
14'''
15globalcount
16printrow
17count+=1
18
19defdo_queen(i):
20'''生成所有正确解
21@parami:
皇后的数目
22'''
23forjinrange(0,8):
#依次尝试0~7位置
24ifcol[j]==1andpos_diag[i-j+7]==1andnag_diag[i+j]==1:
#若该行,正对角线,负对角线上都没有皇后,则放入i皇后
25row[i]=j
26col[j]=0#调整各个列表状态
27pos_diag[i-j+7]=0
28nag_diag[i+j]=0
29ifi<7:
30do_queen(i+1)#可递增或递减
31else:
32output()#产生一个结果,输出
33col[j]=1#恢复各个列表状态为之前的
34pos_diag[i-j+7]=1
35nag_diag[i+j]=1
36
37if__name__=='__main__':
38col=[]#矩阵列的列表,存储皇后所在列,若该列没有皇后,则相应置为1,反之则0
39row=[]#矩阵行的列表,存放每行皇后所在的列位置,随着程序的执行,在不断的变化中,之间输出结果
40pos_diag=[]#正对角线,i-j恒定,-7~0~7,并且b(i)+7统一到0~14
41nag_diag=[]#负对角线,i+j恒定,0~14
42count=0
43forindexinrange(0,8):
#一些初始化工作
44col.append
(1)
45row.append(0)
46forindexinrange(0,15):
47pos_diag.append
(1)
48nag_diag.append
(1)
49do_queen(0)#开始递归,先放一个,依次递增,反过来,从7开始递减也可
50print'Totallyhave%dsolutions!
'%count
51
o运行截屏
CDays-2
1.在文中grep实现例子中,没有考虑子目录的处理,因为如果直接open目录进行读操作会出现错误,所以要求读者修改这个示例
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 可爱 python 习题 答案