ImageVerifierCode 换一换
格式:DOCX , 页数:28 ,大小:70.03KB ,
资源ID:4766424      下载积分:5 金币
验证码下载
登录下载
邮箱/手机:
图形码:
验证码: 获取验证码
温馨提示:
支付成功后,系统会自动生成账号(用户名为邮箱或者手机号,密码是验证码),方便下次登录下载和查询订单;
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

开通VIP
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.zixin.com.cn/docdown/4766424.html】到电脑端继续下载(重复下载【60天内】不扣币)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录  

开通VIP折扣优惠下载文档

            查看会员权益                  [ 下载后找不到文档?]

填表反馈(24小时):  下载求助     关注领币    退款申请

开具发票请登录PC端进行申请。


权利声明

1、咨信平台为文档C2C交易模式,即用户上传的文档直接被用户下载,收益归上传人(含作者)所有;本站仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。所展示的作品文档包括内容和图片全部来源于网络用户和作者上传投稿,我们不确定上传用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的版权、权益或隐私,请联系我们,核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
2、文档的总页数、文档格式和文档大小以系统显示为准(内容中显示的页数不一定正确),网站客服只以系统显示的页数、文件格式、文档大小作为仲裁依据,个别因单元格分列造成显示页码不一将协商解决,平台无法对文档的真实性、完整性、权威性、准确性、专业性及其观点立场做任何保证或承诺,下载前须认真查看,确认无误后再购买,务必慎重购买;若有违法违纪将进行移交司法处理,若涉侵权平台将进行基本处罚并下架。
3、本站所有内容均由用户上传,付费前请自行鉴别,如您付费,意味着您已接受本站规则且自行承担风险,本站不进行额外附加服务,虚拟产品一经售出概不退款(未进行购买下载可退充值款),文档一经付费(服务费)、不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
4、如你看到网页展示的文档有www.zixin.com.cn水印,是因预览和防盗链等技术需要对页面进行转换压缩成图而已,我们并不对上传的文档进行任何编辑或修改,文档下载后都不会有水印标识(原文档上传前个别存留的除外),下载后原文更清晰;试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓;PPT和DOC文档可被视为“模板”,允许上传人保留章节、目录结构的情况下删减部份的内容;PDF文档不管是原文档转换或图片扫描而得,本站不作要求视为允许,下载前可先查看【教您几个在下载文档中可以更好的避免被坑】。
5、本文档所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用;网站提供的党政主题相关内容(国旗、国徽、党徽--等)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
6、文档遇到问题,请及时联系平台进行协调解决,联系【微信客服】、【QQ客服】,若有其他问题请点击或扫码反馈【服务填表】;文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“【版权申诉】”,意见反馈和侵权处理邮箱:1219186828@qq.com;也可以拔打客服电话:4009-655-100;投诉/维权电话:18658249818。

注意事项

本文(《Python程序设计基础与应用(第2版)》习题答案.docx)为本站上传会员【二***】主动上传,咨信网仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知咨信网(发送邮件至1219186828@qq.com、拔打电话4009-655-100或【 微信客服】、【 QQ客服】),核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载【60天内】不扣币。 服务填表

《Python程序设计基础与应用(第2版)》习题答案.docx

1、第2版 Py亨。n程序设计基 机工致育 面向新工科高等院校大数据专业系列教材 信息技术新工科产学研联盟数据科学与大数据工作委员会推荐教材 《Python程序设计基础与应用(第2版) 章节习题答案董付国 Python ProgramrningPython*鳄设计 基础与应用I第2版i 董付国著 畅销经典全新升级:配备时长达27小时的100个微课 视频,融入思政教学元素,数据可视化图形全彩呈现实用性强:精心设计的百余个教学案例契合高校Python课程教学 实际,精准匹配大数据相关专业及非计算机专业教学需求 j己套资源丰云:配备教学PPT、程序源代码、教学大纲、习题及习题 答案

2、在线练习软件等全套教学资源G机械工业出版社 Yl/ CHINA MACHINE PRESS result = result + treturn result print(func(3J 4)) def func(s): return s == s[::-1]ss = (1 PythonL C, 'Go', '雾锁山头山锁雾’,’天连水尾水连天’) for s in ss: print(sJ func(s)sep= *:')5. def myCycle(iterable): temp = tuple(iterable) while True: for item in temp:

3、 yield item c = myCycle(1 Python 小屋’) for i in range(20): print(next(c))6. def myCount(start^ step): while True: yield startstart = start + step c = myCount(3> 2)for i in range(20): print(next(c)) def myReversed(seq): for item in seq[::-1]: yield item rev = myReversed([1^ 2> 3]) print(rev)

4、print(list(rev))8. def myAll(iterable): for item in iterable: if not item: return Falsereturn True print(myAll([l, 2, 3]))print(myAllCf"Python 小屋’])) 9. def myAny(iterable): for item in iterable: if item: return Truereturn False print(myAny([l, 2, 3])) print(myAny([1 ', 'Python 小屋1 ])) pr

5、int(myAny(['1, 0,[]]))10. 13 1615 11. def rate(origin^ userinput): if not (is instance (origin., str) and isinstance( user Inputs str)): print(*The two parameters must be strings.1) return right = sum(map(lambda oc> uc:oc==uc, origin, userinput)) return round(right/len(origin)? 2)si = 1 Readabi

6、lity counts.1 s2 = 1 readability count.*print(rate(si> s2)) 12. from random import randintdef guess(start? stop> maxTimes): #随机生成一个整数 value = randint(starts stop)for i in range(maxTimes): prompt =,开始猜吧:1 if i==0 else,再猜一次:1 x = int(input(f'猜数范围:【{start},{stop}], {prompt}1)) if x == value: pri

7、nt('恭喜,猜对了 !’)break elif x > value: print('太大了o 1)else: print厂太小了。1) else: printC次数用完了,游戏结束。’)print('正确的数字是:L value) guess(100^ 110^ 3)13. from random import random def helper(i): x = random() y = random() return x*x + y*y <= 1def estimatePI(times): hits = sum(map(helper^ range(times))) r

8、eturn 4.0 * hits/timesprint(estimatePI(10000)) print(estimatePI(1000000))print(estimatePI(100000000)) print(estimatePI(1000000000))第6章面向对象程序设计 1. class2. +3. in对5.错6.错7.错8.错 9. 答: 1)把数据及其对应的操作封装到一起组成类的概念,对外部只提供必要的访问接口。 2)继承是一种设计复用的概念,以设计良好的类作为基类,创建派生类并根据需要增加 新的成员或修改已有的成员,使得设计可以延续,并且减少工作量,减少出错的

9、可能。 3)多态是指基类中的方法和行为在不同的派生类对象中有不同的表现。 10. class Vector3: #构造方法,初始化,定义向量坐标 def _init_(self, x> y> z): self._x = xself._y = y self, z = z #与两一个向量相加,对应分量相加,返回新向量 def add(self) anotherPoint): if not isinstance(anotherPointVector3): printC参数类型不对。’)return x = self._x + anotherPoint._xy = self._y

10、 + anotherPoint._y z = self._z + anotherPoint._zreturn Vector3(x^ y, z) #减去另一个向量,对应分量相减,返回新向量 def sub(selfanotherPoint): x = self._x - anotherPoint._x y = self._y - anotherPoint._y z = self._z - anotherPoint._z return Vector3(x^ y> z) #向量与一个数字相乘,各分量乘以同一个数字,返回新向量 def mul(selfn): x, y, z = self._

11、x*n, self._*n, self._z*n return Vector3(x^ y, z) #向量除以一个数字,各分量除以同一个数字,返回新向量 def div(self, n): x, y, z = self._x/n, self._/n> self._z/n return Vecto「3(x> y, z) #查看向量各分量值 def show(self): print(’X:{}, Y:{}, Z:{}'.format(self._x,self._ > self ._z)) #查看向量长度,所有分量平方和的平方根 @property def length(self)

12、 return (self._x**2 + self._**2 + self._z**2)**0.5 #内积 def dot(selfother): t = self._x*other._x + self._y*other._y + self._z*other._zreturn t ** 0.5 #用法演示v = Vector3(3J 4, 5) vl = v.mul(3) vl.show()v2 = vl.add(v) v2. show() print(v2.length) print(vl.dot(v2))11. class Array: def _init_(self

13、seq): self._data = list(seq)def_setitem_(selfindex> value): self._data[index] = value def _str_(self): return f'Array((self._data))'repr_ = _str arr = Array([1^ 2, 3]) arr[2] = 666 print(arr)12. class Array: def _init_(selfseq): self._data = list(seq)def _getitem_(self, index): temp =[] for i in

14、 index: temp.append(self._data[i]) return temparr = Array(range(10)) print(arr[[3,2,l,5]]) 字符串1. 14 2. 213.5 4. 85. 6 6. 127. 7 8. True9. False 10. #遍历字符串中所有字符 #遇到数字,记录到临时变量 def longest(s): result =[] t =[] for ch in s: if ,0,<=ch<=,9,: t.append(ch)elif t: result .append(1 1

15、 . join(t)) #遇到非数字,把临时的连续数字记下来 t =[] if t:#考虑原字符串以数字结束的情况result.append(11.join(t)) if result: return max(resultkey=len) return '没有数字字符。1s = ,2022-01-15Python小屋刷题软件拥有2066道客观题和426道编程题。* print(longest(s)) 11. def func(s): return ' 1.join(reversed(s.split())) print(func(11 love beijing.1))12. de

16、f func(s): return sorted(set(s)> key=s.rindex) print(func(1abcda1))print(func(* abcbda1)) 第8章 正则表达式 1. 4 2. 'afff1 3. [3, 'I' 5. ['1', 2, 3, '41] 6. 4 8. ? 9. ,albbbblcldle, 10. A 11. D 12. B 14.对 15.对 16. 对 4. P、R7. 6 13. B17.对 18.对 19. from re import findallfilename

17、 1 test,py1 with open(filenameJ encoding=1utf8') as fp: content = fp.read()content) content) func_names = findall(1 \s*?def\s+?(\w+?)\(. + ?: 1 if func_names: print(func_names)else: printC1程序中没有函数。*) 20. from re import findallfilename = 'test.py1 with open(filename., encoding=1 utf81) as f

18、p: content = fp.readlines()for index, line in enumerate(content^ start=l): pattern = 1 (?, line) if result: t = result[0].strip().split(',')print(f'第{index}行发现普通变量:{t}') pattern = 1 as (\w+?):1 result = findall(pattern^ line) if result: print(F第{index}

19、行发现 as 变量:(result}') pattern = 'for (.+?) in 1 result = findall(patternJ line) if result: t = result [0]. strip(). split (1,, 1)print(F第{index}行发现for循环变量:{t}') pattern = 1\s*?def \w*?\((・+?)\):' result = findall(patternJ line) if result: t = result[0].strip().split(', ')print(f'第{index}行发现函数

20、形参:{t}1) 21. import redef checkModify(s): return re.sub(r,\b(\w)(\w+)(\w)\b',lambda x: x.group(l)+x.group(2)・lower()+x・group(3), s) print(checkModify(1aBc ABBC D eeee fFFFfF1))第9章 文件与文件夹操作 1. fileNamel = input(1 Input a fileName: 1) fileName2 = input(1 Input another fileName: 1)with open(1resu

21、lt.txt1'w', encoding=1utf81) as fp: with open(fileNamelJ encoding=1utf81) as open(fileName2^ encoding=1utf81) as fp2: while True: linel = fpl.readline() if linel: fp.write(linel)else: flag = False break line2 = fp2.readline() if line2: fp.write(line2)else: flag = True breakfp3 = fpl if flag el

22、se fp2 for line in fp3: fp.write(fp3.readline())2. filename = 1 merge.py1with open(filename^ 1r'encoding=1utf81) as fp: lines = fp.readlines() maxLength = len(max(lines^ key=len))lines = [line.rstrip().Ijust(maxLength)+f*# (index}\n1 for index, line in enumerate(lines)]with open (filename [: - S

23、j + ^new.py1'w', encoding=1 utf8') as fp: fp.writelines(lines)3. from os.path import exists from os import listdir^ remove import openpyxl#结果文件名,如果己存在,先删除 result = 1 result.xlsx1if exists(result): remove(result)#创建空白结果文件,并添加表头 #假设所有表格都只具有学院、姓名、成绩这3列 第1章Python概述1. ABCD 2. ABCD 3. BD 4.略 5.略 6.

24、略答: 1)使用"import包名/模块名[as别名]”这种方式将包或模块导入以后,使用时需 要在对象之前加上模块名作为前缀,必须以“模块名.对象名”的形式进行访问。如果模块 名字很长,可以为导入的模块设置一个别名,然后使用“别名.对象名”的方式来使用其中 的对象。 2)使用“from包名/模块名import模块名/对象名[as别名]”方式仅导入明确指 定的模块或对象,并且可以为导入的对象起一个别名。这种导入方式可以减少查询次数, 提高访问速度,同时也可以减少程序员需要输入的代码量,不需要使用包名或模块名作为 前缀。 3)使用"from包名/模块名import*”方式可以一次导入包名/模

25、块中的所有对象, 简单直接,比较省事,可以使用包名/模块中的所有对象而不需要再使用包名/模块名作 为前缀,但一般并不推荐这样使用。 7. 答: 通过Python程序的_name_属性可以识别程序的使用方式,如果作为模块被导入, 则其_name_属性的值被自动设置为模块名;如果作为程序直接运行,则其_name_属 性值被自动设置为字符串’main L第2章 内置对象、运算符、表达式、关键字 1. //2. |3. -4. &5. A

26、npyxl.Workbook()wsResult = wbResult.worksheets[0] wsResult.append([1 学院1, 1 姓名 1,'成绩,])#遍历当前文件夹中所有xlsx文件, #把除表头之外的内容追加到结果文件中fns = (fn for fn in listdir() if fn.endswith(*.xlsx')) for fn in fns: ws = openpyxl.load_workbook(fn).worksheets[0] for index, row in enumerate(ws.rows): #跳过表头if index ==

27、 0: continuewsResult.append(list(map(lambda cell:cell・value, row))) #保存结果文件wbResult ・ save(result) 4. from docx import Documentdoc = Document(^est.docx1) for table in doc.tables: for row in table.rows: for cell in row.cells: print(cell.textend=1 1) print()5. from os import listdirfrom os.pa

28、th import join, isdir^ isfile, getctime from datetime import date root = 1D:\\'def check(root): try: items = listdir(root) except: return for item in items: item = join(rootitem)if isdir(item): check(item)elif isfile(item) and item.endswith('temp.txt'): print(item) check(root)6. from os im

29、port listdirfrom os.path import join., isdir, isfile? getctime from datetime import dateroot = 1D:\\1 def check(root): try: items = listdir(root) except: return for item in items: item = join(root^ item)if isdir(item): check(item)elif isfile(item): c_date = date.fromtimestamp(getctime(item

30、)) if c_date == date(2021J 1饥 26): print(item)check(root) 7. from os import listdir^ makedirsfrom os.path import abspath, isdir^ isfile, exists, join from filecmp import cmp from shutil import copyfile def autoBackup(scrDir_, dstDir): if not (isdir(scrDir) and isdir(dstDir) andabspath(scrDir)==

31、scrDir and abspath(dstDir)==dstDir): printC两个参数都必须是已存在的绝对路径。*) return for item in listdir(scrDir): scrltem = join(scrDir\ item)dstltem = scrltem. replace (sc rDir.,dstDir) if isdir(scrltem): if not exists(dstltem):#确保目标文件夹的结构与原始文件夹一致makedirs(dstltem) print(^ake directory ^dstltem) autoBackup(s

32、crltemdstltem)elif isfile(scrltem):#只复制新增或修改过的文件 if not (exists(dstltem) and cmp(scrltemj dstltem^ shallow=False)): copyfile(scrltem^ dstltem) print('file:1+scrltem+'==>,+dstItem)scrDir = r1D:\WorkingDirectory1 dstDir = r1D:\BackupDirectory1autoBackup(scrDir., dstDir) 8. from os import listdirma

33、kedirsfrom os.path import abspath, isdir^ isfile, exists, join from filecmp import cmpfrom shutil import copyfile def autoBackup(scrDir^ dstDir): if not (isdir(scrDir) and isdir(dstDir) and abspath(scrDir)==scrDir and abspath(dstDir)==dstDir): print('两个参数都必须是巳存在的绝对路径。’)return for item in listdi

34、r(scrDir): scrltem = join(scrDir> item)dstltem = scrltem.replace(scrDirdstDir) if isdir(scrltem): if not exists(dstltem):#确保目标文件夹的结构与原始文件夹一致makedirs(dstltem) print('make directory,+dstItem) autoBackup(scrltem, dstltem)elif isfile(scrltem):#只复制新增或修改过的文件 if not (exists(dstltem) and cmp(scrltemj d

35、stltem^ shallow=False)): copyfile(scrltem^ dstltem)print('file:l+scrItem+,==>'+dstItem) scrDir = input(1请输入工作目录:’)dstDir = input(1请输入备份目录:’) autoBackup(scrDir., dstDir) 第1。章异常处理结构1. fileNamel = input('Input a fileName: 1) fileName2 = input(1 Input another fileName:')try: fp = open('result・txt',

36、'w', encoding=1utf81) except: printC创建文件失败。•) exit()try: fpl = open(fileNamelJ encoding=1utf81) fp2 = open(fileName2J encoding=1utf81) except: printC打开文件失败,请检查路径和拼写是否正确。,) exit()while True: linel = fpl.readline() if linel: fp.write(linel) else: flag = Falsebreak line2 = fp2.readline() if

37、 line2: fp.write(line2) else: flag = Truebreak fp3 = fpl if flag else fp2for line in fp3: fp・ write(fp3 ・ readline())fpl.close() fp2.close()fp.close() 2. from os import listdir., makedirsfrom os.path import abspath, isdir^ isfile^ exists, join from filecmp import cmpfrom shutil import copyf

38、ile def autoBackup(scrDir> dstDir): condition = (isdir(scrDir) and isdir(dstDir) andabspath(scrDir)==scrDir and abspath(dstDir)==dstDir) assert condition,,两个参数都必须是己存在的绝对路径。' for item in listdir(scrDir): scrltem = join(scrDirJ item)dstltem = scrltem. replace (sc rDir., dstDir) if isdir(scrltem

39、): if not exists(dstltem):#确保目标文件夹的结构与原始文件夹一致makedirs(dstltem) print(^ake directory1+dstItem)autoBackup(scrltem,, dstltem) elif isfile(scrltem):#只复制新增或修改过的文件if not (exists(dstltem) and cmp(scrltemj dstltem, shallow=False)): copyfile(scrltem., dstltem) print('file:1+scrltem+1==>1+dstItem) scrDir

40、 input(1请输入工作目录:’)dstDir = input厂请输入备份目录:') autoBackup(scrDir., dstDir)3. dictionary = {'a*: 97, 'b‘: 98, 'c‘: 99, 'd‘: 100) while True: key = input(1请输入任意内容:,) if key.lower() == 'quit': break try: print(f'对应的值为:{dictionary[key]}') except: print(,不存在。’)from random import randint try: star

41、t = int(input('请输入整数 start: 1)) end = int(input('请输入整数 end: 1)) assert end >= startexcept: print(1必须输入整数,且必须end>=starto ')else: print(randint(starts end))第11章网络爬虫入门与应用 1. method2. href3. urlopen()4. headerscontent6・ startproject7. crawl8. runspider 8. start_urls10. from re import findallfrom ur

42、llib.parse import urljoin from urllib.request import urlopen^ Requesturl = r1 http:1 headers = ( 1 User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.361,1Referer *: url) req = Request(url=url^ headers=headers)with urlopen

43、req) as fp: content = fp.read().decode() pattern = r1 ( . + ?) 1for filellrlj fileName in findall(pattern^ content): if Javascript1 in fileUrl: continue filellrl = urljoin(urlJ fileUrl) req = Request(url=filellrlJ headers=headers) with urlopen(req) as fpl: with

44、open(fileName^ 1wb') as fp2: fp2.write(fpl.read())11. from urllib.request import urlopenwith urlopen(r1http://ip.42.pl/raw') as fp: print(fp.read().decode()) 12. import reimport os import os.pathfrom time import sleep from urllib.parse import urljoinfrom urllib.request import urlopen dstDir =

45、1YuanShi1if not os.path.isdir(dstDir): os.mkdir(dstDir)url = with urlopen(url) as fp: content = fp.read().decode()pattern = ('

  • (. + ?),)result = re.findall(pattern., content) for perUrlj name in result: perUrl = urljoin(url>

    46、perUrl) name = os. path. join(dstDirname) print(perUrl) with urlopen(perllrl) as fp: content = fp.read().decode() pattern = r1

    (.+?)

    1 intro = re.findall(patterncontentre.M) if intro: intro = 1\n1.join(intro) intro = re.sub('( )|( )|(
    )111intro) with open(name+tx

    47、t', encoding=1utf8') as fp: fp.write(intro) sleep(3)第12章pandas数据分析与处理 1. by2. describe() 4. drop_duplicates() 7. diff() 8. read_ _excel() 10.对 11.对 12.对 15.错 16.错 17.错 20.对 21.对 22.对 25.对 26.对 27.对 30. 3. nlargest() 5. inplace 6. groupby() 9. read_csv() 13.对 14. 对 18

    48、对 19. 对 23.对 24. 对 28.对 29. 对 from operator import pandas from operator import pandas import itemgetter as pd df = pd.read_excel('电影导演演员.xlsx')df .演员=d千.演员.str.split(', 1) df = df .explode('演员 1) .drop(1 导演axis=l)df = df.groupby('演员',as_index=False ).apply(lambda group: 1,

    49、 1.join(map(itemgetter(0)^ group.values))) df.columns =['演员’电影名称’]df .电影名称=df .电影名称.str. split(1, 1) .map(set) result =[饥()]for i in df.index[:-1]: for j in df.index[i+l:]: num = len(df.loc[i,,电影名称’]& df.loc[j,,电影名称’])if num > result[0]: result = [num, (i,j)]print (df. loc[ list (result [1]) '演员'].values) 31. from copy import deepcopy import pandas as pdimport matplotlib.pyplot as pit pit.rcParams['font.sans-serif1] = [1simhei'] df = pd.read_csv(1 data.csv1encoding=1cp9361)df = df.dropna() dfl = deepcopy(df)# dfl[1 month 1] = dfl

  • 移动网页_全站_页脚广告1

    关于我们      便捷服务       自信AI       AI导航        抽奖活动

    ©2010-2025 宁波自信网络信息技术有限公司  版权所有

    客服电话:4009-655-100  投诉/维权电话:18658249818

    gongan.png浙公网安备33021202000488号   

    icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

    关注我们 :微信公众号    抖音    微博    LOFTER 

    客服