Python大数据基础与实战范晖课后题答案Word下载.docx
《Python大数据基础与实战范晖课后题答案Word下载.docx》由会员分享,可在线阅读,更多相关《Python大数据基础与实战范晖课后题答案Word下载.docx(16页珍藏版)》请在冰豆网上搜索。
2:
3
14.
inputthreenumbers:
a,b,c=map(int,x.split())
sortedresultis:
sorted((a,b,c)))
第3章
1.
importrandom
x=[random.randint(0,200)foriinrange(100)]
#第一种实现:
使用集合
s=set(x)
forvins:
print(v,'
:
x.count(v))
#第二种实现:
使用字典
d=dict()
forvinx:
d[v]=d.get(v,0)+1
fork,vind.items():
print(k,v,sep='
2.
inputalist:
x=eval(x)
p=input("
inputtwopositon:
begin,end=map(int,p.split())
print(x[begin:
end+1])
3.[6foriinrange(10)]
4.
x=[random.randint(0,100)foriinrange(20)]
print(x)
x[:
10]=sorted(x[:
10])
x[10:
]=sorted(x[10:
],reverse=True)
5.[]
6.[18,19]
7.([1,3],[2])
8.当列表增加或删除元素时,列表对象自动进行内存扩展或收缩,从而保证元素之间没有缝隙,但这涉及到列表元素的移动,效率较低,应尽量从列表尾部进行元素的增加与删除操作以提高处理速度。
9.[1,2,3,1,2,3,1,2,3]
10.['
1'
'
2'
3'
]
第4章
1.A2.D3.C4.D5.C
6.
name=input("
请输入你的名字:
"
place=input("
请输入你经常去的地方:
like=input("
请输入你平时的爱好:
print('
可爱的'
name,'
'
最喜欢在'
place,'
地方进行'
like)
或者:
test="
可爱的{0},最喜欢在{1}地方进行{2}"
v=test.format(name,place,like)
print(v)
7.
s=input("
请输入一个待统计的字符串:
print(s.count("
))
第5章
1.Continue、break
2.while
3.C
4.B
5.Python提供了while和for两种循环控制结构,用来处理需要进行的重复操作,直到满足某些特定条件。
while循环一般用于循环次数难以提前确定的情况,也可以用于循环次数确定的情况。
for循环一般用于循环次数可以提前确定的情况,尤其适用于枚举或者遍历序列、迭代对象中元素的场合。
for循环写的代码通常更加清晰简单,因此编程时建议优先使用for循环。
相同或不同的循环结构之间可以相互嵌套,也可以和选择结构嵌套使用,用来实现更为复杂的逻辑。
6.
Pleaseinputaninteger:
x=int(x)
ifx%2==0:
print("
{:
d}is偶数!
.format(x))
d}is奇数!
7.
Pleaseinputanintegerlessthan1000:
t=x
i=2
result=[]
whileTrue:
ift==1:
break
ift%i==0:
result.append(i)
t=t//i
else:
i+=1
print(x,'
='
*'
.join(map(str,result)))
第6章
importmath
defIsPrime(v):
n=int(math.sqrt(v)+1)
foriinrange(2,n):
ifv%i==0:
return'
No'
else:
return'
Yes'
print(IsPrime(17))
print(IsPrime(30))
print(IsPrime(813))
defdemo(v):
capital,little,digit,other=(0,)*4#或者capital=little=digit=other=0
foriinv:
if'
A'
<
=i<
='
Z'
capital+=1
elif'
a'
z'
little+=1
0'
9'
digit+=1
other+=1
return(capital,little,digit,other)
x='
PEP498,formattedstringliterals.'
print(demo(x))
3.会。
defdemo():
a=3
print(a)
a=5
demo()
defmySum(data):
sum=0
fordindata:
sum+=d
returnsum
5.
defmySorted(lst,reverse=False):
lst=lst[:
length=len(lst)
foriinrange(0,length-1):
forjinrange(i+1,length):
#比较相邻两个元素大小,并根据需要进行交换
#默认升序排序
exp='
lst[i]>
lst[j]'
#如果reverse=True则降序排序
ifreverse:
exp='
lst[i]<
ifeval(exp):
lst[i],lst[j]=lst[j],lst[i]
returnlst
6.-2
7.
defdemo(*v):
print(max(v))
print(sum(v))
8.deff(n):
a=b=c=1
foriinrange(n-3):
c,b,a=a+b+c,c,b
returnc
第7章
1.B2.C3.D4.C5.A
6.
classStudent:
#学生类
count=0#计数
def__init__(self,name,age):
self.name=name
self.age=age
Student.count+=1#要使得变量全局有效,就定义为类的属性
deflearn(self):
islearning"
stu1=Student("
jack"
33)
stu2=Student("
amy"
24)
stu3=Student("
lucy"
22)
stu4=Student("
lulu"
45)
实例化了%s个学生"
%Student.count)
classB:
def__init__(self):
pass
defhandle(self):
B.handle"
classA(B):
super().__init__()
super().handle()#super依赖于继承
a=A()
a.handle()
第8章
1.C2.A3.D4.B5.A
try:
score=int(input("
请输入学生的成绩:
ifscore>
=90andscore<
=100:
A:
优秀"
elifscore>
=80andscore<
90:
B:
良好"
=60andscore<
80:
C:
合格"
else:
assertscore>
60,"
D:
不及格"
exceptExceptionasresult:
低于60分:
\n"
result)
classmy_error(Exception):
def__init__(self,stri):
self.leng=len(stri)
defprocess(self):
ifself.leng<
5:
return'
Theinputisoflength%s,expectingatleast5'
%self.leng
printsuccess'
s=input("
请输入字符串:
raisemy_error(s)
exceptmy_errorase:
print(e.process())
第9章
1.C2.D3.D4.A5.B
oldFileName=input("
请输入要拷贝的文件名字:
oldFile=open(oldFileName,'
r'
ifoldFile:
#提取文件的后缀
fileFlagNum=oldFileName.rfind('
.'
iffileFlagNum>
0:
fileFlag=oldFileName[fileFlagNum:
#组织新的文件名
newFileName=oldFileName[:
fileFlagNum]+'
[复件]'
+fileFlag
#创建新文件
newFile=open(newFileName,'
w'
#把旧文件中的数据复制到新文件中
forlineContentinoldFile.readlines():
newFile.write(lineContent)
#关闭文件
oldFile.close()
newFile.close()
importos
importsys
sys.setrecursionlimit(1000)#setthemaximumdepthas1500
file_path=input('
请输入待查找的目录:
file_name=input('
请输入待查找的文件:
deffile_find(file_path,file_name):
ifos.path.isdir(file_path):
#os.chdir(file_path)#进入当前路径
ile_list=os.listdir(file_path)
foreachinfile_list:
temp_dir=file_path+os.sep+each
ifos.path.isdir(temp_dir):
#开始递归进入下一级子目录
temp=file_find(temp_dir,file_name)
iftemp==True:
returnTrue
elifos.path.isfile(temp_dir)andeach==file_name:
returnTrue
#os.chdir('
..'
)#没找到文件,退回上一个目录
returnFalse
print('
{}不是一个目录'
.format(file_path))
file_path='
\PythonTest\book1'
file_name='
1.txt'
print(file_find(file_path,file_name))
第10章
1.B2.C3.A4.D5.C
6.
(1)
%matplotlibinline
importmatplotlib.pyplotasplt
importseabornassns
iris=sns.load_dataset("
iris"
sns.set(style="
ticks"
fig,axes=plt.subplots(1,2,figsize=(20,5))
sns.swarmplot(x='
petal_length'
y="
petal_width"
ax=axes[0],data=iris,hue="
species"
sepal_length'
sepal_width"
ax=axes[1],data=iris,hue="
plt.show()
(2)
sns.lmplot("
petal_length"
"
hue="
markers=["
x"
o"
s"
],data=iris)
从回归图上可以看出这两个特征之间是线性相关的。
第11章
1.B、C
2.D
4.C
5.
importnumpyasnp
arr=np.random.rand(10,5)
matr1=np.arange(1,5).reshape(2,2)
matr2=np.arange(5,9).reshape(2,2)
matr1*matr2
7.v=np.array([1,-1,1]).reshape(3,1).T
P=(v*v.T)/(v.T*v)
Q=np.eye(3,3)-P
8.dir(np);
np.arange?
9.np.array([[1,-1,0]])生成一个(1,3)的矩阵,np.array([1,-1,0])生成一个向量。
第12章
1.A2.D3.D4.A5.B6.B
(1)
mpg=sns.load_dataset("
mpg"
mpg.ndim
mpg.size
mpg.describe()
(3)
mpg.groupby('
cylinders'
)['
mpg'
horsepower'
].agg("
mean"
origin'
第13章
fromlxmlimportetree
importrequests
response=requests.get("
response.encoding="
utf-8"
selector=etree.HTML(response.text)
news_text=selector.xpath('
//*[@id="
u1"
]/a[1]/text()'
)[0]
news_url=selector.xpath('
]/a[1]/@href'
2.
1)创建scrapy项目
scrapystartprojectsdWeatherSpider
2)创建爬虫程序
scrapygenspidereveryCitySD
3)使用浏览器打开网址
4)在页面上单击鼠标右键,选择“查看网页源代码”,找到与“城市预报列表”对应的位置。
选择并打开陕西省内任意城市的天气预报页面,以西安为例。
选择“查看页面源代码”,找到与天气预报相对应的位置。
5)修改items.py文件,定义要爬虫的内容
importscrapy
classSdweatherspiderItem(scrapy.Item):
city=scrapy.Field()
weather=scrapy.Field()
6)修改爬虫文件everyCitySD.py
#-*-coding:
utf-8-*-
fromreimportfindall
fromsdWeatherSpider.itemsimportSdweatherspiderItem
classEverycitysdSpider(scrapy.Spider):
allowed_domains=['
name='
everyCitySD'
start_urls=['
url=r'
response=requests.get(url)
response.encoding="
contents=response.text
pattern='
<
atitle="
.*?
href="
(.+?
)"
target="
_blank"
>
.+?
/a>
forurlinfindall(pattern,contents):
#获取地市级预报的网页地址
start_urls.append(url)
defparse(self,response):
item=SdweatherspiderItem()
city=response.xpath('
//div[@class="
crumbsfl"
]//a[2]//text()'
).extract()[0]
item['
city'
]=city
selector=response.xpath('
//ul[@class="
tclearfix"
]'
weather='
forliinselector.xpath('
./li'
):
date=li.xpath('
./h1//text()'
cloud=li.xpath('
./p[@title]//text()'
high=li.xpath('
./p[@class="
tem"
]//span//text()'
low=li.xpath('
]//i//text()'
wind=li.xpath('
win"
]//em//span[1]/@title'
wind=wind+li.xpath('
weather=weather+date+'
+cloud+'
+high+'
/'
+low+'
+wind+'
\n'
weather'
]=weather
return[item]
7)修改pipelines.py文件,把爬取的数据写入文件weather.csv
importcsv
classSdweatherspiderPipeline(object):
defprocess_item(self,item,spider):