python生成數(shù)據(jù)課后習(xí)題答案_第1頁(yè)
python生成數(shù)據(jù)課后習(xí)題答案_第2頁(yè)
python生成數(shù)據(jù)課后習(xí)題答案_第3頁(yè)
python生成數(shù)據(jù)課后習(xí)題答案_第4頁(yè)
python生成數(shù)據(jù)課后習(xí)題答案_第5頁(yè)
免費(fèi)預(yù)覽已結(jié)束,剩余11頁(yè)可下載查看

付費(fèi)下載

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、Solutions-Chapter1515-1:CubesAnumberraisedtothethirdpowerisacube.Plotthefirstfivecubicnumbers,andthenplotthefirst5000cubicnumbers.Plotting5cubes:frommatplotlibimportpyplotasplt#Definedata.x_values=1,cubes=1,8,2,3,4,527,64,125#Makeplot.plt.scatter(x_values,cubes,edgecolor=none,s=40)#Customizeplot.plt

2、.title(Cubes,fontsizeplt.xlabel(Value,fontsizeplt.ylabel(CubeofValueplt.tick_params(axis=both=24)=14),fontsize,labelsize=14)=14)#Showplot.plt.show()Output:Plotting5000cubes:frommatplotlibimportpyplotasplt#Definedata.x_values=list(range(5001)cubes=x*3forxinx_values#Makeplot.plt.scatter(x_values,cubes

3、,edgecolor#Customizeplot.plt.title(Cubes,fontsize=24)plt.xlabel(Value,fontsize=14)plt.ylabel(CubeofValue,fontsizeplt.tick_params(axis=both,labelsizeplt.axis(0,5100,0,5100*3)#Showplot.Output:qwuww=none,s=40)=14)=14)15-2:ColoredCubesApplyacolormaptoyourcubesplot.frommatplotlibimportpyplotasplt#Defined

4、ata.x_values=list(range(5001)cubes=x*3forxinx_values#Makeplot.plt.scatter(x_values,cubes,edgecolorcmap=plt.cmBuGn,s=40)#Customizeplot.plt.title(Cubes,fontsize=24)plt.xlabel(Value,fontsize=14)plt.ylabel(CubeofValue,fontsize=14)plt.tick_params(axis=both,labelsize=14)plt.axis(0,5100,0,5100*3)#Showplot.

5、plt.show()Cubes由 Il3器.nnwaflci5節(jié)&口=none,c=cubes,Output:15-3:MolecularMotionModifyrw_visual.pybyreplacingplt.scatter()withplt.plot().tosimulatethepathofapollengrainonthesurfaceofadropofwater,passintherw.x_valuesandrw.y_values,andincludealinewidthargument.Use5000insteadof50,000points.importmatplotlib.

6、pyplotaspltfromrandom_walkimportRandomWalk#Keepmakingnewwalks,aslongastheprogramisactive.whileTrue:#Makearandomwalk,andplotthepoints.rw=RandomWalk(5000)rw.fill_walk()#Setthesizeoftheplottingwindow.plt.figure(dpi=128,figsize=(10,6)point_numbers=list(range(rw.num_points)plt.plot(rw.x_values,rw.y_value

7、s,linewidth=1)#Emphasizethefirstandlastpoints.plt.scatter(0,0,c=green,edgecolors=none,s=75)plt.scatter(rw.x_values-1,rw.y_values-1,c=rededgecolors=none,s=75)#Removetheaxes.plt.axes().get_xaxis().set_visible(False)plt.axes().get_yaxis().set_visible(False)plt.show()keep_running=input(Makeanotherwalk?(

8、y/n):)ifkeep_running=n:breakOutput:Thescatterplotsappearbehindthelines.Toplacethemontopofthelines,wecanusethezorderargument.Plotelementswithhigherzordervaluesareplacedontopofelementswithlowerzordervalues.importmatplotlib.pyplotaspltfromrandom_walkimportRandomWalk#Keepmakingnewwalks,aslongastheprogra

9、misactive.whileTrue:#Makearandomwalk,andplotthepoints.rw=RandomWalk(5000)rw.fill_walk()#Setthesizeoftheplottingwindow.plt.figure(dpi=128,figsize=(10,6)point_numbers=list(range(rw.num_points)plt.plot(rw.x_values,rw.y_values,linewidth=1,zorder=1)#Emphasizethefirstandlastpoints.plt.scatter(0,0,c=green,

10、edgecolors=none,s=75,zorder=2)plt.scatter(rw.x_values-1,rw.y_values-1,c=red,edgecolors=none,s=75,zorder=2)#Removetheaxes.plt.axes().get_xaxis().set_visible(False)plt.axes().get_yaxis().set_visible(False)plt.show()keep_running=input(Makeanotherwalk?(y/n):)ifkeep_running=n:breakOutput:15-5:Refactoring

11、Themethodfill_walk()islengthy.Createanewmethodcalledget_step()todeterminethedirectionanddistanceforeachstep,andthencalculatethestep.Youshouldendupwithtwocallstoget_step()infill_walk():x_step=get_step()y_step=get_step()Thisrefactoringshouldreducethesizeoflll_walk()andmakethemethodeasiertoreadandunder

12、stand.random_walk.py:classRandomWalk():Aclasstogeneraterandomwalks.def_init_(self,num_points=5000):Initializeattributesofawalk.self.num_points=num_points#Allwalksstartat(0,0).self.x_values=0self.y_values=0defget_step(self):Determinethedirectionanddistanceforastep.direction=choice(1,-1)distance=choic

13、e(0,1,2,3,4)step=direction*distancereturnstepdeffill_walk(self):Calculateallthepointsinthewalk.#Keeptakingstepsuntilthewalkreachesthedesiredlength.whilelen(self.x_values)self.num_points:#Decidewhichdirectiontogo,andhowfartogointhatdirection.x_step=self.get_step()y_step=self.get_step()#Rejectmovestha

14、tgonowhere.ifx_step=0andy_step=0:continue#Calculatethenextxandyvalues.next_x=self.x_values-1+x_stepnext_y=self.y_values-1+y_stepself.x_values.append(next_x)self.y_values.append(next_y)Output:15-6:AutomaticLabelsModifydie.pyanddice_visual.pybyreplacingthelistweusedtosetthevalueofhist.x_labelswithaloo

15、ptogeneratethislistautomatically.Ifyourecomfortablewithlistcomprehensions,tryreplacingtheotherforloopsindie_visual.pyanddice_visual.pywithcomprehensionsaswell.Note:Thisshouldsaytomodifydie_visual.py,notdie.py.Thiswillbecorrectedinfutureprintings.die_visual.py:importpygal#CreateaD6.die=Die()#Makesome

16、rolls,andstoreresultsinalist.results=die.roll()forroll_numinrange(1000)#Analyzetheresults.frequencies=results.count(value)forvalueinrange(1,die.num_sides+1)#Visualizetheresults.hist=pygal.Bar()hist.add(D6,frequencies)hist.render_to_file(die_visual.svg)dice_visual.py:importpygalfromdieimportDie#Creat

17、etwoD6dice.die_1=Die()die_2=Die()#Makesomerolls,andstoreresultsinalist.results=die_1.roll()+die_2.roll()forroll_numinrange(1000)#Analyzetheresults.max_result=die_1.num_sides+die_2.num_sidesfrequencies=results.count(value)forvalueinrange(2,max_result+1)#Visualizetheresults.hist=pygal.Bar()hist.title=

18、ResultsofrollingtwoD6dice1000times.hist.title=ResultsofrollingoneD61000times.hist.x_labels=str(x)forxinrange(1,diehist.x_title=Resulthist.y_title=FrequencyofResult.num_sides+1)hist.x_labels=str(x)forxinrange(2,max_result+1)hist.x_title=Resulthist.y_title=FrequencyofResulthist.add(D6+D6,frequencies)h

19、ist.render_to_file(dice_visual.svg)15-7:TwoD8sCreateasimulationshowingwhathappensifyourolltwoeight-sideddice1000times.Increasethenumberofrollsgraduallyuntilyoustarttoseethelimitsofyoursystemscapabilities.importpygalfromdieimportDie#CreatetwoD8dice.die_1=Die(8)die_2=Die(8)#Makesomerolls,andstoreresul

20、tsinalist.results=forroll_numinrange(1000000):result=die_1.roll()+die_2.roll()results.append(result)#Analyzetheresults.frequencies=max_result=die_1.num_sides+die_2.num_sidesforvalueinrange(2,max_result+1):frequency=results.count(value)frequencies.append(frequency)#Visualizetheresults.hist=pygal.Bar(

21、)hist.title=ResultsofrollingtwoD8dice1,000,000times.hist.x_labels=str(x)forxinrange(2,max_result+1)hist.x_title=Resulthist.y_title=FrequencyofResulthist.add(D8+D8,frequencies)hist.render_to_file(dice_visual.svg)Note:Thissolutiononlyusesalistcomprehensionforthehist.x_labelsotherloopswithcomprehension

22、saswell.Output:parameter.YoumightwanttotryreplacingtheResultsofrollingtwoD8dice1,900,000time.15-8:ThreeDiceIfyourollthreeD6dice,thesmallestnumberyoucanrollis3andthelargestnumberis18.CreateavisualizationthatshowswhathappenswhenyourollthreeD6dice.importpygalfromdieimportDie#CreatethreeD6dice.die_1=Die

23、()die_2=Die()die_3=Die()#Makesomerolls,andstoreresultsinalist.results=口forroll_numinrange(1000000):result=die_1.roll()+die_2.roll()+die_3.roll()results.append(result)#Analyzetheresults.frequencies=口max_result=die_1.num_sides+die_2.num_sides+die_3.num_sidesforvalueinrange(3,max_result+1):frequency=re

24、sults.count(value)frequencies.append(frequency)#Visualizetheresults.hist=pygal.Bar()hist.title=ResultsofrollingthreeD6dice1,000,000times.hist.x_labels=str(x)forxinrange(3,max_result+1)hist.x_title=Resulthist.y_title=FrequencyofResulthist.add(D6+D6+D6,frequencies)hist.render_to_file(dice_visual.svg)N

25、ote:Thissolutiononlyusesalistcomprehensionforthehist,x_labelsparameter.Youmightwanttotryreplacingtheotherloopswithcomprehensionsaswell.Output:15-9:MultiplicationWhenyourolltwodice,youusuallyaddthetwonumberstogethertogettheresult.Createavisualizationthatshowswhathappensifyoumultiplythesenumbersinstead.fromdieimportDie#Cre

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論