版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
《Python程序设计基础(微课版在线练习与考试软件版)》习题答案ISBN:978-7-115-69135-4董付国,人民邮电出版社
第1章Python开发环境搭建与使用(共20题)一、填空题1.pip 2.whl 3.math.factorial(20) 4.random 5.pillow二、选择题1.A 2.C 3.BD 4.CD 5.ABCD 三、判断题1.错 2.错 3.错 4.错 5.错四、简答题1.略 2.略 3.略五、操作题1.略 2.略第2章内置类型、内置函数与运算符(共29题)一、填空题1.3 2.-4 3.-1 4.-3 5.3 6.57.{1} 8.{1,2,3,4} 9.False 10.False二、选择题1.B 2.A 3.D 4.C 5.B三、判断题1.对 2.错 3.对 4.对 5.错6.错 7.对 8.错 9.错 10.错四、程序设计题1.A=eval(input('请输入集合A:'))B=eval(input('请输入集合B:'))print(f'{A|B=}\n{A&B=}\n{A-B=}\n{B-A=}\n{A^B=}')2.data=eval(input('输入包含若干正整数的列表:'))result=list(filter(lambdanum:num>8andnum%2==0,data))print(result)3.keys=eval(input('输入包含若干正整数的列表keys:'))values=eval(input('输入包含若干正整数的列表values:'))result=dict(zip(keys,values))print(result)4.integers=eval(input('请输入包含若干正整数的列表:'))#方法一max_last_digit=str(max(integers,key=lambdanum:str(num)[-1]))[-1]result=[numfornuminintegersifstr(num)[-1]==max_last_digit]print(result)#方法二max_last_digit=max([num%10fornuminintegers])result=[numfornuminintegersifnum%10==max_last_digit]print(result)第3章程序控制结构(共25题)一、填空题1.True 2.True 3.break 4.continue 5.86.123456二、选择题1.D 2.A 3.ABCD 4.ACD 5.AB6.ABCD三、判断题1.对 2.错 3.错 4.错 5.错6.对 7.错 8.错四、程序设计题1.fromrandomimportrandint,choicescharacters='董付国系列教材山东烟台樱桃玉孙兆房桌场艳玲'for_inrange(100):rnd=randint(1,100)ifrnd>30:k=3elifrnd>10:k=2else:k=4name=''.join(choices(characters,k=k))print(name)2.num=1foriinrange(4):num=(num+1)*2print(num)3.#方法一fromitertoolsimportcountforfirstincount(1,1):floors=[first*(2**i)foriinrange(8)]ifsum(floors)==765:forindex,valueinenumerate(floors,start=1):print(f'第{index}层有{value}盏琉璃灯')break#方法二first=765/sum([2**iforiinrange(8)])iffirst.is_integer():floor=firstforiinrange(1,9):print(f'第{i}层有{floor}盏琉璃灯')floor=floor*24.fromitertoolsimportpermutations#10个数字中任选2个不同数字的所有排列digits='0123456789'forch1,ch2inpermutations(digits,2):ifch1==ch2:continue#前两位相同,后两位相同,前后不相同num=int(ch1*2+ch2*2)#恰好是一个整数的平方if(num**0.5).is_integer():print(num)5.fromitertoolsimportcombinationsforkinrange(1,4):foritemincombinations(('麻汁','辣椒油','蒜蓉','香菜'),r=k):if{'麻汁','辣椒油'}<set(item):continueprint(('小咸菜',)+item)第4章列表与元组(共32题)一、填空题1.-3 2.True、True 3.True、False 4.[3,4,5]5.[4,1,2,3] 6.False 7.(1,2) 8.[111,33,2]二、选择题1.A 2.C 3.C 4.A 5.A6.B 7.B 8.ABCD 三、判断题1.错 2.错 3.对 4.错 5.错 6.对 7.错8.错 9.错 10.错四、编程题1.fromfunctoolsimportreducedata=[[1,2,3],[4,5,6],[7,8,9]]print(reduce(lambdar1,r2:[x+yforx,yinzip(r1,r2)],data))2.data=eval(input('输入包含任意内容的列表:'))print(max(set(data),key=data.count))3.whileTrue:try:m=int(input('输入m:'))assertm>1breakexcept:print('无效输入,',end='')whileTrue:try:n=int(input('输入n:'))assertn>1breakexcept:print('无效输入,',end='')matrix=[]foriinrange(m):whileTrue:try:row=eval(input(f'输入第{i+1}行:'))except:print('无效输入,',end='')continueif(isinstance(row,list)andlen(row)==nandset(map(type,row))=={int}andall(map(lambdanum:1<=num<100,row))):matrix.append(row)breakelse:print('无效输入,',end='')print(*matrix,sep='\n')print(sum(map(lambdai:matrix[i][i],range(min(m,n)))))4.fromoperatorimportadd,sub,mulvector1=[1,3,9,30]vector2=[-5,-17,22,0]print(vector1,vector2,sep='\n')print('向量相加:')print(list(map(add,vector1,vector2)))print('向量相减:')print(list(map(sub,vector1,vector2)))print('向量内积:')print(sum(map(mul,vector1,vector2)))print('向量与标量相除:')print(list(map(lambdanum:num/5,vector1)))5.k=int(input('请输入一个正整数:'))numbers=list(range(1,11))#游戏一直进行到只剩下最后一个人for_inrange(len(numbers)-1):for_inrange(k-1):numbers.append(numbers.pop(0))numbers.pop(0)print(f'最后一个人的编号为:{numbers[0]}')6.diag=eval(input('输入一个包含若干整数的列表:'))n=len(diag)matrix=[]foriinrange(n):matrix.append([0]*n)matrix[i][i]=diag[i]print(*matrix,sep='\n')第5章字典与集合(共50题)一、填空题1.get() 2.{1:2,2:3} 3.97 4.99 5.'b' 6.True7.{1,2} 8.{3} 9.False 10.True 11.{1}12.{1} 13.3 14.False 15.4二、选择题1.D 2.C 3.C 4.A 5.A 6.D 7.C8.A 9.D 10.D 11.A 12.C 13.A 14.ABE15.ABCE三、判断题1.错 2.错 3.错 4.对 5.错 6.错 7.错8.错 9.错 10.对 11.错 12.对 13.对 14.错15.对四、程序设计题1.scores={'张三':{'语文':80,'数学':90,'英语':90},'李四':{'语文':87,'数学':89,'英语':86},'王五':{'语文':66,'数学':88,'英语':77}}forname,scoreinscores.items():print(f'{name}总分:{sum(score.values())}')forsubjectinscores['张三'].keys():score=[item[subject]foriteminscores.values()]print(f'{subject}平均分:{sum(score)/len(score)}')2.fromrandomimportrandrangefromitertoolsimportcombinationsdata={f'name{i}':{f'film{randrange(1,20)}'for_inrange(20)}foriinrange(10)}print(*data.items(),sep='\n')result=max(combinations(data.keys(),2),key=lambdaitem:len(data[item[0]]&data[item[1]]))print(result)print(data[result[0]]&data[result[1]])3.fromstringimportascii_letterss=input('输入任意内容:')print(set(s)<=set(ascii_letters))4.keys=eval(input('输入一个列表:'))try:tuple(map(hash,keys))except:print('数据不符合要求')else:values=eval(input('再输入一个列表:'))print(dict(zip(keys,values)))5.text='''Beautifulisbetterthanugly.Explicitisbetterthanimplicit.Simpleisbetterthancomplex.Complexisbetterthancomplicated.Flatisbetterthannested.Sparseisbetterthandense.Readabilitycounts.Specialcasesaren'tspecialenoughtobreaktherules.Althoughpracticalitybeatspurity.Errorsshouldneverpasssilently.Unlessexplicitlysilenced.Inthefaceofambiguity,refusethetemptationtoguess.Thereshouldbeone--andpreferablyonlyone--obviouswaytodoit.Althoughthatwaymaynotbeobviousatfirstunlessyou'reDutch.Nowisbetterthannever.Althoughneverisoftenbetterthan*right*now.Iftheimplementationishardtoexplain,it'sabadidea.Iftheimplementationiseasytoexplain,itmaybeagoodidea.Namespacesareonehonkinggreatidea--let'sdomoreofthose!'''lines=text.splitlines()rule=lambdaline:len(set(line))/len(line)>0.5print(*filter(rule,lines),sep='\n')第6章字符串(共43题)一、填空题1.True 2.False 3.False 4.'3' 5.-16.True 7.r、R 8.8 9.'sdf' 10.511.10 12.True 13.20 14.'C' 15.764116.'a:b:cd'二、选择题1.A 2.C 3.B 4.B 5.B 6.B 7.A8.A三、判断题1.对 2.错 3.错 4.对 5.错 6.错 7.错8.对 9.对 10.对 11.对 12.对 13.对 14.错15.对四、程序设计题1.s=input('输入任意内容:')forindex,chinenumerate(s):ifs.index(ch)==s.rindex(ch):print((ch,index))2.s=input('输入任意内容:')result=''.join(sorted(set(s),key=s.index))print(result)3.fromrandomimportrandintfromjiebaimportcutdefswap(word):'''交换长度为2的单词中的两个字顺序'''iflen(word)==2andrandint(1,100)>50:word=word[1]+word[0]returnwordtext=input('请输入一段中文:')words=cut(text)print(''.join(map(swap,words)))4.num=int(input('输入一个正整数:'))num_bin=bin(num)print(len(num_bin)-len(num_bin.rstrip('0')))第7章函数定义与使用(共32题)一、填空题1.None 2.global 3.['abcd'] 4.[1,2,3] 5.-46.'xyz' 7.666 8.555 9.True 10.(3,4)11.2,5,b,二、选择题1.C 2.B 3.AC 4.ABCD 5.ABCD 6.ABCD三、判断题1.对 2.对 3.错 4.错 5.错 6.错 7.错8.对 9.错 10.错四、程序设计题1.importsysfromfunctoolsimportlru_cachesys.setrecursionlimit(3000)@lru_cache(maxsize=64)defcni(n,i):ifn==iori==0:return1returncni(n-1,i)+cni(n-1,i-1)print(cni(600,100))2.deffunc(factors,x):result=factors[0]forfactorinfactors[1:]:result=result*x+factorreturnresultfactors=[(3,8,5,9,7,1),(5,0,0,0,0,1),(5,),(5,1)]forfactorinfactors:print(func(factor,2))3.defmy_filter(func,iterable):iffuncisNone:func=boolforiteminiterable:iffunc(item):yielditemprint(tuple(my_filter(str.isdigit,'1234abc5')))print(tuple(my_filter(lambdaitem:len(item)>3,('aaaa','b'))))print(tuple(my_filter(None,[0,1,2,'','a'])))4.fromfunctoolsimportreducedefgcd(m,n):whileTrue:r=m%nifr==0:returnnm,n=n,rprint(reduce(gcd,[30,40,50,60]))5.deffunc(x):ifx<0:return0elifx<5:returnxelifx<10:return3*x-5elifx<20:return0.5*x-2else:return0forxinrange(-5,25):print(x,func(x),sep=':')第8章文件操作(共40题)一、填空题1.mode 2.encoding 3.with 4.'w' 5.listdir()6.getsize() 7.getcwd() 8.exists() 9.isfile() 10.isdir()11.remove() 12.startfile() 13.dirname() 14.getmtime() 15.join() 16.basename() 17.data_only二、选择题1.AB 2.ABC 3.BCD 4.AB 5.AB 6.ABC 7.B8.A 9.D三、判断题1.错 2.错 3.错 4.对 5.对 6.对 7.错8.错 9.错 10.错四、编程题1.fromcollectionsimportCounterfromstringimportpunctuationwithopen(r'C:\Python310\news.txt',encoding='utf8')asfp:content=fp.read()words=content.split()forindex,wordinenumerate(words):ifword.endswith(tuple(punctuation)):words[index]=word.rstrip(punctuation)words=list(filter(None,words))print(Counter(words).most_common(10))2.fromosimportlistdirfromos.pathimportjoin,isdirdeflistDirWidthFirst(directory):number=0dirs=[directory]whiledirs:current=dirs.pop(0)try:forsubPathinlistdir(current):path=join(current,subPath)ifisdir(path):dirs.append(path)elifpath.endswith('.txt'):number=number+1except:passreturnnumberprint(listDirWidthFirst('C:\\'))3.fromdocximportDocumentfromposerimportComposerdefmain(files,final_docx):new_document=Document()composer=Composer(new_document)forfninfiles:composer.append(Document(fn))composer.save(final_docx)main(['1.docx','2.docx','3.docx'],'result2.docx')4.fromosimportremovefromdocx2pythonimportdocx2pythonfromPILimportImageobj=docx2python('E:/带公式的文档.docx')forname,imageDatainobj.images.items():ifname.endswith('.wmf'):#保存wmf格式的矢量图形withopen(name,'wb')asfp:fp.write(imageData)#把wmf格式的矢量图形转换为png格式的图像withImage.open(name)asim:#使用高分辨率加载图形,默认分辨率72dpi比较模糊im.load(dpi=300)im.save(name[:-3]+'png')#删除wmf文件remove(name)第9章面型对象程序设计(共25题)一、填空题1.class 2.def 3.+ 4.in 5.self6.@property 7.True 8.True 9.@classmethod 10.>=二、判断题1.对 2.错 3.错 4.错 5.错6.对 7.对 8.对 9.错 10.对三、简答题1.答:1)把数据及其对应的操作封装到一起组成类的概念,对外部只提供必要的访问接口。2)继承是一种设计复用的概念,以设计良好的类作为基类,创建派生类并根据需要增加新的成员或修改已有的成员,使得设计可以延续,并且减少工作量,减少出错的可能。3)多态是指基类中的方法和行为在不同的派生类对象中有不同的表现。2.答:1)_xxx:以一个下画线开头,表示保护成员,一般在当前类或子类中访问这些成员,不建议通过对象直接访问;在模块中使用一个或多个下画线开头的成员不能用“frommoduleimport*”导入,除非在模块中使用__all__变量明确指明这样的成员可以被导入。2)__xxx:以两个下画线开头但不以两个下画线结束,表示私有成员,一般只有类对象自己能访问,子类对象也不能访问该成员,但在对象外部可以通过“对象名._类名__xxx”这样的特殊形式来访问。3)__xxx__:前后各两个下画线,系统定义的特殊成员。四、编程题1.classVector3:#构造方法,初始化,定义向量坐标def__init__(self,x,y,z):self.__x=xself.__y=yself.__z=z#与两一个向量相加,对应分量相加,返回新向量defadd(self,anotherPoint):ifnotisinstance(anotherPoint,Vector3):print('参数类型不对。')returnx=self.__x+anotherPoint.__xy=self.__y+anotherPoint.__yz=self.__z+anotherPoint.__zreturnVector3(x,y,z)#减去另一个向量,对应分量相减,返回新向量defsub(self,anotherPoint):x=self.__x-anotherPoint.__xy=self.__y-anotherPoint.__yz=self.__z-anotherPoint.__zreturnVector3(x,y,z)#向量与一个数字相乘,各分量乘以同一个数字,返回新向量defmul(self,n):x,y,z=self.__x*n,self.__y*n,self.__z*nreturnVector3(x,y,z)#向量除以一个数字,各分量除以同一个数字,返回新向量defdiv(self,n):x,y,z=self.__x/n,self.__y/n,self.__z/nreturnVector3(x,y,z)#查看向量各分量值defshow(self):print('X:{},Y:{},Z:{}'.format(self.__x,self.__y,self.__z))#查看向量长度,所有分量平方和的平方根@propertydeflength(self):return(self.__x**2+self.__y**2+self.__z**2)**0.5#内积defdot(self,other):t=self.__x*other.__x+self.__y*other.__y+self.__z*other.__zreturnt**0.5#用法演示v=Vector3(3,4,5)v1=v.mul(3)v1.show()v2=v1.add(v)v2.show()print(v2.length)print(v1.dot(v2))2.classArray:def__init__(self,seq):self.__data=list(seq)def__setitem__(self,index,value):self.__data[index]=valuedef__str__(self):returnf'Array({self.__data})'__repr__=__str__arr=Array([1,2,3])arr[2]=666print(arr)3.classArray:def__init__(self,seq):self.__data=list(seq)def__getitem__(self,index):temp=[]foriinindex:temp.append(self.__data[i])returntemparr=Array(range(10))print(arr[[3,2,1,5]])第10章综合应用开发(共25题)一、填空题1.Tk() 2.mainloop() 3.Button 4.textvariable 5.command6.urlopen() 7.Request 8.runspider 9.openai二、判断题1.对 2.对 3.对 4.对 5.对6.对 7.对 8.对 9.对 10.对11.对 12.对 13.对四、编程题1.importreimporttkinterimporttkinter.messageboxroot=tkinter.Tk()#设置窗口初始大小和位置,300和270之间是小写字母x,不是乘号root.geometry('300x270+400+100')root.resizable(False,False) #不允许改变窗口大小root.title('简易计算器') #设置窗口标题#放置用来显示信息的文本框,并设置为只读contentVar=tkinter.StringVar(root,'')contentEntry=tkinter.Entry(root,textvariable=contentVar)contentEntry['state']='readonly'contentEntry.place(x=10,y=10,width=280,height=20)defbuttonClick(btn): #按钮通用代码content=contentVar.get()ifcontent.startswith('.'): #如果已有内容是以小数点开头的,前面加0content='0'+content#根据不同按钮做出相应的处理ifbtnin'0123456789': #输入数字时直接接在表达式最后content+=btnelifbtn=='.': #输入小数点时检查是否合理lastPart=re.split(r'\+|-|\*|/',content)[-1] #使用正则表达式切分表达式得到所有操作数if'.'inlastPart:tkinter.messagebox.showerror('错误','小数点太多了')returnelse:content+=btnelifbtn=='C': #单击Clear按钮时清空表达式content=''elifbtn=='=': #输入等号时计算表达式的值try:content=str(eval(content)) #对输入的表达式求值except:tkinter.messagebox.showerror('错误','表达式错误')returnelifbtninoperators: #单击运算符按钮时检查是否合理ifcontent.endswith(operators):tkinter.messagebox.showerror('错误','不允许存在连续运算符')returncontent+=btnelifbtn=='Sqrt': #计算平方根n=content.split('.')ifall(map(lambdax:x.isdigit(),n)): #表达式为实数,计算平方根content=eval(content)**0.5else:tkinter.messagebox.showerror('错误','表达式错误')returncontentVar.set(content) #更新界面上文本框中的表达式#放置清除按钮和等号按钮btnClear=tkinter.Button(root,text='Clear',command=lambda:buttonClick('C'))btnClear.place(x=40,y=40,width=80,height=20)btnCompute=tkinter.Button(root,text='
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 商场财务票据管理制度汇编(3篇)
- 值班无可疑人员管理制度(3篇)
- 工地疫情物资发放管理制度(3篇)
- 公司培训学院管理制度范本(3篇)
- 2026及未来5年中国光电医美设备行业市场研究分析及投资前景研判报告
- 制剂处方辅料数据化管理平台建设
- 创新药供应链物流成本的特殊性与控制
- 创伤评分可视化与急诊医疗资源合理配置
- 创伤后气道重建的手术策略-1
- 会阴裂伤护理应急预案演练
- 2026年山东理工职业学院综合评价招生《素质测试》模拟试题
- 2025年莱芜职业技术学院单招职业适应性测试题库附答案解析
- 八年级地理下册:黄土高原区域发展与居民生活的可持续性探究
- 新能源运维技术支持工程师面试题及答案
- 2026年度医院纪检监察工作计划(2篇)
- 心脏移植术后CRT治疗的药物调整方案
- 教学副校长学校管理述职报告
- 《新能源汽车构造与故障检修》实训工单
- 【低空经济】低空经济职业学院建设方案
- (正式版)DB54∕T 0275-2023 《民用建筑节能技术标准》
- 破产管理人模拟试题及答案
评论
0/150
提交评论