资源描述
第2版
Py亨。n程序设计基
机工致育
面向新工科高等院校大数据专业系列教材
信息技术新工科产学研联盟数据科学与大数据工作委员会推荐教材
《Python程序设计基础与应用(第2版)
章节习题答案董付国
Python ProgramrningPython*鳄设计
基础与应用I第2版i
董付国著
畅销经典全新升级:配备时长达27小时的100个微课 视频,融入思政教学元素,数据可视化图形全彩呈现实用性强:精心设计的百余个教学案例契合高校Python课程教学 实际,精准匹配大数据相关专业及非计算机专业教学需求
j己套资源丰云:配备教学PPT、程序源代码、教学大纲、习题及习题 答案、在线练习软件等全套教学资源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: 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) 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 ])) print(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 Readability 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:
print('恭喜,猜对了 !’)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))) return 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)继承是一种设计复用的概念,以设计良好的类作为基类,创建派生类并根据需要增加 新的成员或修改已有的成员,使得设计可以延续,并且减少工作量,减少出错的可能。
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 + 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._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):
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_(selfseq): 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 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 . 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.
def 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 = 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 fp: content = fp.readlines()for index, line in enumerate(content^ start=l): pattern = 1 (?<!\()(. + ?) = 1 result = findall(pattern>, 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}行发现 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}行发现函数形参:{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(1result.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 else 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 [: - Sj + ^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.略答:
1)使用"import包名/模块名[as别名]”这种方式将包或模块导入以后,使用时需 要在对象之前加上模块名作为前缀,必须以“模块名.对象名”的形式进行访问。如果模块 名字很长,可以为导入的模块设置一个别名,然后使用“别名.对象名”的方式来使用其中 的对象。
2)使用“from包名/模块名import模块名/对象名[as别名]”方式仅导入明确指 定的模块或对象,并且可以为导入的对象起一个别名。这种导入方式可以减少查询次数, 提高访问速度,同时也可以减少程序员需要输入的代码量,不需要使用包名或模块名作为 前缀。
3)使用"from包名/模块名import*”方式可以一次导入包名/模块中的所有对象, 简单直接,比较省事,可以使用包名/模块中的所有对象而不需要再使用包名/模块名作 为前缀,但一般并不推荐这样使用。
7. 答:
通过Python程序的_name_属性可以识别程序的使用方式,如果作为模块被导入, 则其_name_属性的值被自动设置为模块名;如果作为程序直接运行,则其_name_属 性值被自动设置为字符串’main L第2章 内置对象、运算符、表达式、关键字
1. //2. |3. -4. &5. A<B 6. 1:2:3
7. len()8. 21
9. 710. -5
11. True 12. False
wbResult = openpyxl.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 == 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.path 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 import 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)) 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)==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(scrltemdstltem)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 listdirmakedirsfrom 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 listdir(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 dstltem^ 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', '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 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 copyfile
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):
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 = 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:
start = 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 urllib.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(req) as fp: content = fp.read().decode()
pattern = r1 <a href=M (. + ?) Hxspan>( . + ?)</span> 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 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 = 1YuanShi1if not os.path.isdir(dstDir):
os.mkdir(dstDir)url = with urlopen(url) as fp:
content = fp.read().decode()pattern = (' <li class=,,name_list,,xa href=n (. + ?)"1
1 target=,,_blankH>(. + ?)</ax/li>,)result = re.findall(pattern., content) for perUrlj name in result:
perUrl = urljoin(url> perUrl)
name = os. path. join(dstDirname)
print(perUrl)
with urlopen(perllrl) as fp:
content = fp.read().decode()
pattern = r1<p>(.+?)</p>1
intro = re.findall(patterncontentre.M)
if intro:
intro = 1\n1.join(intro)
intro = re.sub('( )|( )|(<a href.*?</a>)111intro) with open(name+txt', 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.对
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, 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
展开阅读全文