




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
《Python程序設(shè)計(第3版)》[美]約翰·策勒(JohnZelle)第8章答案True/False1.False2.True3.False4.True5.False6.False7.True8.True9.False10.TrueMultipleChoice1.a2.c3.d4.c5.c6.c7.d8.b9.c10.aDiscussion1.Whileloopfragments:1.2.3.sum=0i=1whilei<=n:sum=sum+ii=i+1sum=0i=1whilei<2*n:sum=sum+ii=i+2sum=0x=input("Enteranumber:")whilex!=999:sum=sum+xx=input("Enteranumber:")
4.count=0whilen>1:n=n/2count=count+1ProgrammingExercises1.解法?defmain():a=0b=1c=1n=int(input("Entern:"))#foriinrange(n-1):i=0whilei<n-1:i=i+1c=a+ba=bb=cprint("Thefigureis{0}.".format(c))main()解法?#c08ex01.py#Nthfibonaccinumberdefmain():print("ThisprogramcalculatesthenthFibonaccivalue.\n")n=int(input("Enterthevalueofn:"))curr,prev=1,1foriinrange(n-2):curr,prev=curr+prev,currprint("ThenthFibonaccinumberis",curr)if__name__=='__main__':main()2.解法?(沒有?好函數(shù)和列表,缺乏簡潔性)defdrawStruct():print('\n|----------------+',end='')foriinrange(8):print('-'*8+'+',end='')print('--------|')defdrawLine():print("|{0:^16}|".format(''),end='')foriinrange(9):print("{0:^8}|".format(''),end='')print()defmain():print('WCI'.center(100))print('-'*99)print("|{0:^15}|".format('V/ML/h\T/℃'),end='')forTinrange(-20,61,10):print("{0:^8}|".format(T),end='')drawStruct()forVinrange(0,55,5):drawLine()print("|{0:^16}|".format(V),end='')forTinrange(-20,61,10):ifV<=3:WCI='/'print("{0:^8}|".format(WCI),end='')else:WCI=35.74+0.6215*T+(0.4275*T-35.75)*(V**0.16)print("{0:^8.2f}|".format(WCI),end='')print()print('-'*99)if__name__=="__main__":main()解法?(最佳解法,值得學習)#c08ex02.py#WindchillTabledefwindChill(t,v):ifv>3:chill=35.74+0.6215*t-35.75*(v**0.16)+0.4275*t*(v**0.16)else:chill=treturnchilldefmain():#Printtableheadingsprint("WindChillTable\n\n")print("Temperature".center(70))print("MPH|",end='')temps=list(range(-20,61,10))fortintemps:print("{0:5}".format(t),end='')print("\n---+"+55*'-')#Printlinesintableforvelinrange(0,51,5):print("{0:3}|".format(vel),end='')fortempintemps:print("{0:5.0f}".format(windChill(temp,vel)),end='')print()print()main()3.defmain():apr=float(input("Entertheinterest:"))n=0while(1+apr)**n<2:n=n+1print('Principalwilldoubleafter{0}years.'.format(n))if__name__=="__main__":main()4defmain():n=int(input('Entern:'))print('Syracuse:',n,end='')whilen!=1:n=syr(n)print(int(n),end='')defsyr(x):ifx%2==0:s=x/2else:s=3*x+1returnsif__name__=='__main__':main()5解法?(更簡潔易懂)defmain():n=int(input('Entern(n>2):'))s=0foriinrange(2,n):ifn%i==0:print(i,end='')s=s+1ifs==0:print(n,'isprime.')if__name__=="__main__":main()解法?(算法結(jié)構(gòu)更?道)#c08ex05.py#PrimalitytesterimportmathdefisPrime(n):ifn%2==0:returnFalsefactor=3whilefactor<=math.sqrt(n):ifn%factor==0:returnFalsefactor=factor+2returnTruedefmain():print("Primenumbertester\n")n=int(input("Enteravaluetotest:"))ifisPrime(n):print(n,"isprime.")else:print(n,"isnotprime.")if__name__=='__main__':main()6解法?defmain():n=int(input('Entern(n>2):'))forjinrange(2,n+1):isPrime(j)defisPrime(n):s=0foriinrange(2,n):ifn%i==0:s=s+1ifs==0:print(n,end='')if__name__=="__main__":main()解法?#c08ex06.pyprimeston#fromc08ex05importisPrimedefmain():print("ThisprogramfindsallprimenumbersuptoN\n")n=int(input("Entertheupperlimit,n:"))print("primes:",end='')foriinrange(2,n+1):ifisPrime(i):print(i,end='')print("Done")if__name__=='__main__':main()7解法?defmain():try:n=int(input('Entern:'))t=0ifn%2==0:m=n//2foriinrange(2,m):ifisPrime(i)+isPrime(n-i)==2:t=t+1print('({0}){1}{2}'.format(t,i,n-i))else:print('Thenumberisnotanevennumber!')except:print('Checkthefigureyouinput!')defisPrime(n):s=0foriinrange(2,n):ifn%i==0:s=s+1ifs==0:return1else:return0if__name__=='__main__':main()解法?#c08ex07.py#Goldbachtesterfromc08ex05importisPrimedefgoldbach(x):cand=3whilecand<x/2:other=x-candifisPrime(cand)andisPrime(other):returncandcand=cand+2defmain():print("Goldbachchecker\n")n=int(input("Enteranevennaturalnumber:"))ifn%2!=0:print(n,"isnoteven!")else:prime1=goldbach(n)prime2=n-prime1print("{0}+{1}={2}".format(prime1,prime2,n))if__name__=='__main__':main()8.defmain():m=int(input('Enterm:'))n=int(input('Entern:'))whilem!=0:n,m=m,n%mprint('GCD:',n)if__name__=='__main__':main()9解法?defmain():startRoute=float(input('Entertherouteatfirst:'))totalRoute=0totalGas=0i=0whileTrue:rg=input('Entertherouteandgasseperatedby"":').split()ifrg==[]:breaki=i+1route,gas=float(rg[0]),float(rg[1])MPG=(route-startRoute)/gastotalRoute=totalRoute+route-startRoutestartRoute=routetotalGas=totalGas+gasprint('Route{0}MPG:{1:.2f}.'.format(i,MPG))totalMPG=totalRoute/totalGasprint('TotalMPG:{0:.2f}'.format(totalMPG))if__name__=='__main__':main()解法?#c08ex09.py#Programtofigureoutgasmileageoveramultiple-legjourney.defmain():print("Thisprogramcalculatesfuelefficiencyoveramulti-legjourney.")print("Youshouldenterthegallonsofgasconsumedandmilestraveled")print("foreachleg.Justhit<Enter>tosignaltheendofthetrip.")print()distance,fuel=0.0,0.0inStr=input("Entergallonsandmiles(withacommabetween):")whileinStr!="":inputs=inStr.split(",")gallons,miles=int(inputs[0]),int(inputs[1])print("MPGforthisleg:{0:0.1f}".format(miles/gallons))distance=distance+milesfuel=fuel+gallonsinStr=input("Entergallonsandmiles(withacommabetween):")print()print("Youtraveledatotalof{0:0.1f}mileson{1:0.1f}gallons.".format(distance,fuel))print("Thefuelefficiencywas{0:0.1f}milespergallon.".format(distance/fuel))if__name__=='__main__':main()10解法?defmain():fname=input('Enterthenameofthefile:')infile=open(fname,'r',encoding='utf-8')startRoute=float(infile.readline())totalRoute=0totalGas=0i=0forlineininfile.readlines():rg=line.split()ifrg==[]:breaki=i+1route,gas=float(rg[0]),float(rg[1])MPG=(route-startRoute)/gastotalRoute=totalRoute+route-startRoutestartRoute=routetotalGas=totalGas+gasprint('Route{0}MPG:{1:.2f}.'.format(i,MPG))totalMPG=totalRoute/totalGasprint('TotalMPG:{0:.2f}'.format(totalMPG))infile.close()if__name__=='__main__':main()解法?#c08ex10.py#Batchfuelefficiencydefmain():print("Thisprogramcalculatesfuelefficiencyoveramulti-legjourney.")print("Itgetstripinformationfromafile.Eachlineofthefileshould")print("havethegallonsusedandmilestraveled(separatedbyacomma)for")print("onelegofthejourney.\n")fname=input("Whatfilecontainsthedata?")infile=open(fname,'r')distance,fuel=0.0,0.0forlineininfile:inputs=line.split(",")gallons,miles=int(inputs[0]),int(inputs[1])print("Gallons:{0:0.1f},Miles:{1:0.1f},MPG:{2:0.1f}".format(gallons,miles,miles/gallons))distance=distance+milesfuel=fuel+gallonsinfile.close()print("\nYoutraveledatotalof{0:0.1f}mileson{1:0.1f}gallons.".format(distance,fuel))print("Thefuelefficiencywas{0:0.1f}milespergallon.".format(distance/fuel))if__name__=='__main__':main()11解法?defmain():i,hot,cold=1,0,0whileTrue:temperature=input('Entertheaveragetemperatureofday{0}:'.format(i))iftemperature=='':breakt=float(temperature)ift<60:hot=hot+60-tift>80:cold=cold+t-80i=i+1print('Coolingdegree-days:{0}Heatingdegree-days:{1}'.format(cold,hot))if__name__=='__main__':main()解法?(使?max語句替代if語句,更簡潔,經(jīng)驗值得積累)#c08ex11.py#heating/collingdegree-daysdefmain():print("HeatingandCoolingdegree-daycalculation.\n")heating=0.0cooling=0.0tempStr=input("Enteranaveragedailytemperature:")whiletempStr!="":temp=float(tempStr)heating=heating+max(0,60-temp)cooling=cooling+max(0,temp-80)tempStr=input("Enteranaveragedailytemperature:")print("\nTotalheatingdegree-days",heating)print("Totalcoolingdegree-days",cooling)if__name__=='__main__':main()12defmain():print("HeatingandCoolingdegree-daycalculation.")fname=input("Enternameoffilewithaveragetemperaturedata:")infile=open(fname,'r')heating=0.0cooling=0.0forlineininfile:temp=float(line)heating=heating+max(0,60-temp)cooling=cooling+max(0,temp-80)infile.close()print("\nTotalheatingdegree-days",heating)print("Totalcoolingdegree-days",cooling)if__name__=='__main__':main()13解法?fromgraphicsimport*defmain():win=GraphWin('線性回歸?程演?',700,700)win.setBackground('white')win.setCoords(0,0,50,50)frame=Rectangle(Point(0,0),Point(4,2))frame.setFill(color_rgb(0,255,144))frame.draw(win)Text(Point(2,1),'Done').draw(win)sxy,sx,sy,sx2,sy2,n=0,0,0,0,0,0whileTrue:p=win.getMouse()px,py=p.getX(),p.getY()ifpx<=4andpy<=2:breakp.draw(win)sxy=sxy+px*pysx2=sx2+px**2sy2=sy2+py**2sx=sx+pxsy=sy+pyn=n+1a=Circle(Point(sx/n,sy/n),.30)a.setFill('red')a.setOutline('red')a.setWidth(2)a.draw(win)m=(sxy-sx*sy/n)/(sx2-sx*sx/n)n=(sy-sx*m)/nl=Line(Point(0,n),Point(50,m*50+n))l.setWidth(2)l.draw(win)win.getMouse()win.close()if__name__=='__main__':main()解法?fromgraphicsimport*#Thesetwo"constants"aredefinedheresotheycanbeusedinmultiple#functionstodrawthedonebuttonandchecktoseeifitisclickedin.DoneX=1.0#xcoordinateofdonebuttonupperrightDoneY=0.75#ycoordinateofdonebuttonupperrightdefcreateWindow():#Createsa500x500windowtitled"LinearRegression"anddraws###a"DoneButton"inthelowerleftcorner.Thewindowcoordsrunfrom0,0to10,10,andtheupperrightcornerofthebuttonislocatedat(DoneX,DoneY).#Returnsthewindow.win=GraphWin("LinearRegression",500,500)win.setCoords(0,0,10,10)doneButton=Rectangle(Point(.05,0),Point(DoneX,DoneY))doneButton.draw(win)Text(doneButton.getCenter(),"Done").draw(win)returnwindefgetPoint(w):defgetPoint(w):#wisaGraphWin#Pausesforusertoclickinw.Ifuserclickssomewhereotherthan#theDonebutton,thepointisdrawninw.#Returnsthepointclicked,orNoneifuserclickedtheDonebuttonp=w.getMouse()ifp.getX()>DoneXorp.getY()>DoneY:p.draw(w)returnpelse:returnNonedefslope(xb,yb,xx,xy,n):#Returnstheslopeofthelineofbestfit,mreturn(xy-n*xb*yb)/(xx-n*xb*xb)defpredict(x,xb,yb,m):#Returnsapredicatedvaluefory.returnyb+m*(x-xb)defgetPoints(w):#Allowstheusertomakeaseriesofmouseclicksinwuntil#theuserclicksintheDonebutton.#Returns:averageofxvalues####averageofyvaluessumofthesquaresofthexvaluessumofthexyproductsthenumberofpointsclickedbeforeDonesumX=0.0sumY=0.0sumXsq=0.0sumXY=0.0n=0p=getPoint(w)whilep!=None:x,y=p.getX(),p.getY()sumX=sumX+xsumY=sumY+ysumXY=sumXY+x*ysumXsq=sumXsq+x*xn=n+1p=getPoint(w)returnsumX/n,sumY/n,sumXsq,sumXY,ndefmain():#Drawsawindow,getsmouseclicksandthendrawslineofbest#fitthroughthepointsthatwereclicked.win=createWindow()xbar,ybar,sumXsq,sumXY,n=getPoints(win)m=slope(xbar,ybar,sumXsq,sumXY,n)y1=predict(0,xbar,ybar,m)y2=predict(10,xbar,ybar,m)regLine=Line(Point(0,y1),Point(10,y2))regLine.setWidth(2)regLine.draw(win)win.getMouse()win.close()if__name__=='__main__':main()14這是?道很好的題,Image對象很少練習。這道題可做典型。fromgraphicsimport*defopenImage(picFile):img=Image(Point(0,0),picFile)width=img.getWidth()height=img.getHeight()win=GraphWin('',width,height)img.move(width//2,height//2)img.draw(win)returnimgdefconvertToGray(img):forrowinrange(img.getWidth()):forcolinrange(img.getHeight()):r,g,b=img.getPixel(row,col)i=round(0.299*r+0.587*g+0.114*b)img.setPixel(row,col,color_rgb(i,i,i))update()defmain():print("Thisprogramconvertsanimagetograyscale.")inFile=input("Enterthenameofthegiffiletoconvert:")image=openImage(inFile)print('Convertin...',end='')convertToGray(image)print('Done.')outFile=input('Enterfilenamefortheconvertedimage:')image.save(outFile)if__name__=='__main__':main()15fromgraphicsimport
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 足療店成本分析與財務(wù)決策支持系統(tǒng)研究
- 酒店旅游團隊用餐的菜單策劃與實踐案例分享
- 跨國企業(yè)知識產(chǎn)權(quán)培訓的必要性及方法
- 跨平臺設(shè)計軟件的發(fā)展與應(yīng)用分析
- 北京專版2024年中考生物復(fù)習主題訓練四
- 資金管理與企業(yè)價值的創(chuàng)造過程
- 魯京津瓊專用2025版高考數(shù)學大一輪復(fù)習第十一章統(tǒng)計與統(tǒng)計案例11.1隨機抽樣教案含解析
- 通史版2025版高考歷史大一輪復(fù)習專題八近代化的新探索-五四運動到新中國成立前6通史綜合訓練二中國近代史含解析新人教版
- 高中政治1.2科學社會主義的理論與實踐練習1含解析部編版必修1
- 閱讀理解能力與思維能力的提升
- 高速公路綠化工程施工
- 多動癥兒童養(yǎng)育六步法:給家長的自助指南
- 范可尼貧血病癥演示稿件
- 智能制造在食品加工業(yè)中的應(yīng)用與發(fā)展
- 文本排版習題
- 醫(yī)院預(yù)算執(zhí)行情況分析報告
- 年終存貨盤點管理制度
- 化工公司原址污染場地污染土壤治理修復(fù)方案
- 法蘭標準尺寸表(美標、日標、德標)
- 施工技術(shù)管理項總體思路、方式和方法解析
- 《大學生安全教育》課件-第一課 國家安全
評論
0/150
提交評論