




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
課后習題參考答案第一章【參考答案】一、選擇題1.A2.B3.D4.D5.C6.D7.C8.A9.B10.D二、判斷題1.N2.N3.Y4.Y5.N6.Y7.N8.N9.N10.Y三、填空題1.高級語言,匯編語言,機器語言 2.交互方式,文件方式3.help()4.piplist5.input()6.1四、操作題略第二章【參考答案】一、選擇題1.A2.B3.A4.C5.A6.A7.B8.B9.A10.D二、判斷題1.Y2.Y3.N4.N5.N6.Y7.N8.Y9.Y10.Y三、填空題1.6+2j6+2J2.|3.True4.85.有序6.47.False8.[2,3,2,3,2,3]9.[10,13,16,19]10.(True,5)第三章【參考答案】一、選擇題1.C2.D3.C4.C5.D6.B7.C8.A9.B10.C11.C12.C13.D14.D15.A16.A17.C18.C19.D20.A二、判斷題1.Y2.N3.Y4.N5.Y6.Y7.N8.N9.Y10.N三、填空題1._iter_();_next_()2.break3.1611164.1086425.66.267.1;18.sum=16;4;1;79.死循環;Ctrl+C10.Thereversedwordis:dcba;不可以;Thereversedwordis:abcd。四、編程題1.參考代碼:n=int(input("請輸入一個非負整數:"))fac=1whileTrue:ifn>=0:foriinrange(1,n+1):fac*=iprint(fac)breakelse:print("輸入的是負整數,請輸入一個非負整數!")2.參考代碼:importmatha=float(input("請輸入三角形的邊長a:"))b=float(input("請輸入三角形的邊長b:"))c=float(input("請輸入三角形的邊長c:"))ifa+b>candb+c>aanda+c>b:h=(a+b+c)/2s=math.sqrt(h*(h-a)*(h-b)*(h-c))c=a+b+cprint("三角形的面積為:{},邊長為:{}".format(s,c))else:print("輸入的數據有誤!")3.參考代碼:importrandomt=random.randint(0,9)n=0whileTrue:m=int(input("請輸入一個0~9之間的整數:"))n+=1ifm>t:print("很遺憾,太大了!")elifm<t:print("很遺憾,太小了!")else:print("恭喜!猜中了!你一共預測了{}次".format(n))break4.參考代碼:n=9whileTrue:ifn%2==1andn%3==0andn%4==1andn%5==4andn%6==3andn%7==0andn%8==1andn%9==0:print("盒子里面至少有{}顆糖果".format(n))breakelse:n+=1第四章【參考答案】一、選擇題1.B2.C3.A4.B5.D6.B7.A8.B9.B10.D11.C12.D13.D14.D15.C16.C17.C18.A19.D20.C二、判斷題1.Y2.Y3.Y4.N5.N6.N7.N8.N9.Y10.N三、填空題1.['1','2','3']2.0,1,2,3.-14.105.[1,4,7]6.a:97b:98c:997.False8.{1,2}9.’d’10.[3,9,78]四、編程題1.參考代碼:12345n=int(input("請用戶輸入一個整數:"))dt={}foriinrange(1,n+1):dt[i]=i*iprint(dt)2.參考代碼:123456789celebrities=[["希臘","索福克勒斯"],["俄羅斯","普希金"],["法國","莫里哀"],["英國","拜倫"],["中國","老子"],["印度","泰戈爾"],["德國","歌德"],["中國","李白"],["法國","德彪西"]]china_people=[]foritemincelebrities:ifitem[0]=="中國":china_people.append(item[1])print(china_people)3.參考代碼:123456789lines=[]whileTrue:s=input("請輸入一行字母序列:")ifs:lines.append(s.upper())else:breakforsentenceinlines:print(sentence)第五章【參考答案】一、選擇題1.B2.C3.B4.BC5.C6.C7.B8.D9.D10.D二、填空題1.單引號雙引號三單引號三雙引號2.不可0遞增-1遞減3.字符串本身4.拼接/字符串的拼接/字符串拼接復制/字符串的復制/字符串復制包含/包含關系判斷/字符串的包含關系判斷5.len()ord()三、編程題1.參考答案:12345s=input("請輸入身份證號:")
ifint(s[-2])%2==0:
print("女")
else:
print("男")2.參考答案:123456str="helloworld"#ldhellowor
a=int(input("請選擇位移的個數:"))
s=str[-a::1]
z=str[:-a:1]
b=s+z
print(b)第六章【參考答案】一、選擇題1.D2.D3.C4.D5.C6.D7.C8.B9.B10.B11.D12.B二、填空題1.13,16,152.33.-204.85.-26.97.158.可以9.逗號10.局部,全局三、判斷題1.Y2.Y3.Y4.Y5.Y6.Y7.Y8.N9.Y10.N四、編程題1.參考代碼:12345678defdemo(v,n):asserttype(n)==intand0<v<10,'vmustbeintegerbetween1and9'result,t=0,0foriinrange(n):t=t*10+vresult+=treturnresultprint(demo(3,4))2.參考代碼:12345678910111213141516171819202122232425fromrandomimportrandintdefguess(maxValue=100,maxTimes=5):#隨機生成一個整數value=randint(1,maxValue)foriinrange(maxTimes):prompt='StarttoGuess:'ifi==0else'Guessagain:'#使用異常處理結構,防止輸人不是數字的情況try:x=int(input(prompt))except:print('Mustinputanintegerbetween1and',maxvalue)else:#猜對了ifx==value:print('Congratulations!')breakelifx>value:print('Toobig')else:print('Toolittle')else:#次數用完還沒猜對,游戲結束,提示正確答案print('Gameover.FAIL.')print('Thevalueis',value)guess()3.參考代碼:12345defdemo(m,n):p=m*nwhileman!=0:m,n=n,m%nreturn(n,p//n)4.參考代碼:12345678910defyanghui(t):print([1])line=[1,1]print(line)foriinrange(2,t):r=[]forjinrange(0,len(line)-1):r.append(line[j]+line[j+1])line=[1]+r+[1]print(line)5.參考代碼:123456789101112131415161718192021222324252627282930defgetText(text):text=text.lower()forchin",.;?-:\'":text=text.replace(ch,"")returntextdefwordFreq(text,topn):words=text.split()#將文本分詞counts={}forwordinwords:counts[word]=counts.get(word,0)+1excludes={'the','and','to','of','a','be'}forwordinexcludes:del(counts[word])#在字典中刪除無意義單詞items=list(counts.items())#將字典轉換為列表,以方便排序items.sort(key=lambdax:x[1],reverse=True)returnitems[:topn]#返回出現頻率前topn的單詞和頻率計數售text='''Ihaveadreamtoday!Ihaveadreamthatonedayeveryvalleyshallbeexalted,andeveryhillandmountainshallbemadelow,theroughplaceswillbemadeplain,andthecrookedplaceswillbemadestraight;“andthegloryoftheLordshallberevealedandallfleshshallseeittogether."Thisisourhope,andthisisthefaiththatIgobacktotheSouthwith.Withthisfaith,wewillbeabletohewoutofthemountainofdespairastoneofhope.Withthisfaith,wewillbeabletotransformthejanglingdiscordsofournationintoabeautifulsymphonyofbrotherhood.Withthisfaith,wewillbeabletoworktogether,topraytogether,tostruggletogether,togotojailtogether,tostandupforfreedomtogether,knowingthatwewillbefreeoneday.'''text=getText(text)forword,freqinwordFreq(text,20):print("{:<10}{:>}".format(word,freq))print('統計結束')第七章【參考答案】一、選擇題1.C2.C3.D4.B5.B6.C7.D8.D9.D10.D11.C12.D13.B14.A15.A16.D二、填空題1.open()2.flush()3.with4.listdir()5.getcwd()6.mkdir()7.(1)os.getcwd()(2)os.listdir()(3)[fnameforfnameinos.listdir('.')iffname.endswith('.py')](4)os.mkdir(os.getcwd()+'\\t1')(5)os.rename('s.txt',os.getcwd()+'\\t1\\s.txt')(6)os.chdir(os.getcwd()+'\\t1')(7)os.remove('s.txt')三、判斷題1.Y2.N3.Y4.Y5.Y6.Y7.Y8.N9.N10.Y11.Y12.Y13.Y14.N15.Y第八章【參考答案】一、選擇題:1.C2.A3.C4.C5.C6.D7.B二、填空題:1.異常2.單分支選擇3.except4.元組5.finally6.raise7.(1)try:(2)else:(3)list[m:]三、編程題1.參考代碼:123456789101112131415161718#輸入5個整數存于列表,升序排序輸出definnum(list_1):list_1=[]foriinrange(5):try:j=int(input('請輸入一個整數:'))except:print('請輸入整數!')else:list_1.append(j)iflen(list_1)!=5:raiseException('輸入不足五個整數!')else:print("排序后:",sorted(list_1))listnum=[]innum(listnum)2.參考代碼:123456789101112131415161718192021#一元二次方程求兩個實根importmathdeftext(a,b,c):try:ifa==0:raiseValueError('二次項系數不能為0!')ifb*b-4*a*c<=0:raiseException('方程沒有實根!')else:return(a,b,c)exceptExceptionase:print(e)print("輸入一元二次方程各項系數")a=eval(input("輸入a:"))b=eval(input("輸入b:"))c=eval(input("輸入c:"))iftext(a,b,c):print("x1=",(-b+math.sqrt(b*b-4*a*c))/(2*a))print("x2=",(-b-math.sqrt(b*b-4*a*c))/(2*a))第九章【參考答案】一、選擇題1.A2.A3.D4.C5.B二、填空題1.pip,pipinstalljieba2.importjieba3.精確,全模式,搜索引擎4.返回類型5.Jieba,add_word(w)6.importjieba,posseg.psg.cut()7.關鍵詞提取,TF-TDF,TextRank8.importwordcloud,WordCloud(),backgroud_color,max_words、stopwords,generate_from_text,generate_from_frequencies9.['我','在','馬路邊','撿','到','一分錢']10.['市','長江大橋','參觀','了','長江大橋']三、編程題1.參考代碼:123456importjiebas=input()n=len(s)m=len(jieba.lcut(s))print(jieba.lcut(s))print("中文字符數為{},中文詞語數為{}。".format(n,m))2.參考代碼:12345678910111213141516171819202122232425262728importjiebaexcludes={"將軍","卻說","荊州","二人","不可","不能","如此","商議","軍士","如何","主公","軍馬","左右","引兵","次日","大喜","天下","東吳","于是","今日","不敢","魏兵","陛下"}txt=open("三國演義.txt","r",encoding='utf-8').read()words=jieba.lcut(txt)#使用精確模式對文本進行分詞counts={}#通過鍵值對的形式存儲詞語及其出現的次數forwordinwords:iflen(word)==1:#單個詞語不計算在內continueelifword=="孔明"orword=="孔明曰":rword="諸葛亮"elifword=="關公"orword=="云長":rword="關羽"elifword=="玄德"orword=="玄德曰":rword="劉備"elifword=="孟德"orword=="丞相":rword="曹操"else:rword=wordcounts[rword]=counts.get(rword,0)+1forwordinexcludes:#剔除不需要統計的詞delcounts[word]items=list(counts.items())#將鍵值對轉換成列表items.sort(key=lambdax:x[1],reverse=True)#根據詞語出現的次數進行從大到小排序foriinrange(15):word,count=items[i]print("{0:<10}{1:>5}".format(word,count))運行結果:曹操1420諸葛亮1366劉備1204關羽779張飛349呂布299孫權264趙云251司馬懿221周瑜218第十章【參考答案】1.參考代碼:importnumpyasnpimportmatplotlib.pyplotaspltcost=np.array([[1.2,0.9,1.6],[2.2,1.8,2.9],[1.2,0.9,1.5]])product=np.array([[4500,4000,4200,4500],[3000,3500,3200,3200],[5050,6100,5300,6000]])costall=cost.dot(product)print("該工廠四個季度生產A、B、C三種產品所需的成本總和為{}".format(costall.sum()))print("該工廠第一季度生產A、B、C三種產品所需的成本總和為{}".format(costall[:,0].sum()))foriinrange(4):print("該工廠第{}季度原料總成本為{}萬元,人工總成本為{}萬元,管理總成本為{}萬元".format(i+1,costall[0,i],costall[1,i],costall[2,i]))np.savetxt("cost_pr.csv",costall,fmt='%d',delimiter=',')2.參考代碼:importnumpyasnpimportmatplotlib.pyplotaspltimportmatplotlibmatplotlib.rcParams['font.family']='SimHei'#設置中文顯示cost=np.array([[1.2,0.9,1.6],[2.2,1.8,2.9],[1.2,0.9,1.5]])product=np.array([[4500,4000,4200,4500],[3000,3500,3200,3200],[5050,6100,5300,6000]])costall=cost.dot(product)#繪制子圖1plt.subplot(3,1,1)plt.plot([1,2,3,4],product[0,:],[1,2,3,4],product[1,:],[1,2,3,4],product[2,:])plt.xticks([1,2,3,4],["1季度","2季度","3季度","4季度"])plt.xlabel("季度")plt.ylabel("產量")#繪制子圖2plt.subplot(3,1,2)Labels='原料','人工','管理'data=[costall[0,0],costall[1,0],costall[2,0]]Explode=(0,0,0)plt.pie(data,explode=Explode,labels=Labels,autopct='%.2f%%')#繪制子圖3(略)plt.show()第十一章【參考答案】1.編程題123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869505152535455565758596061626364656667686970717273747576777879"""1、從目標url中提取有用的信息,首先分析所給網頁的信息然后根據內容截取信息打印輸出。url:“/api/pub/v1/bcur?bcur_type=11&year=2021”,網頁內容如圖11-14,打印結果如圖11-15。"""importrequestsfrombs4importBeautifulSoupimportbs4importjsonheader={"User-Agent":"Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/79.0.3945.130Safari/537.36"}#從目標url中提取文本信息函數defgetHtmlText(url):try:r=requests.get(url,headers=header,timeout=40)#設置連接成功提醒r.raise_for_status()#改變編碼方式r.encoding=r.apparent_encodingreturnr.textexcept:return""#在所有文本中提取表格前2列信息#json形式存儲數據:#{"code":200,"msg":"success","data":{"rankings":[],"inds":[],"provinces":[],"univCategorys":[]}}'''我們以清華大學數據為例:"data":{"rankings":[{"univUp":"tsinghua-university","univLogo":"logo/27532357.png","univNameCn":"清華大學","univNameEn":"TsinghuaUniversity","inbound":false,"liked":false,"univLikeCount":228,"univTags":["一流大學A類","985","211"],"univNameRemark":"","univCategory":"綜合","province":"北京","score":969.2,"ranking":"1","rankChange":0,"rankOverall":"1","indData":{"159":"37.9","160":"74.3","161":"39.4","162":"48.7","163":"343.0","164":"88.0","165":"37.9","166":"90.8","167":"129.1","168":"80.1"}},...]}'''deffillUnivList(text,num):data=json.loads(text)#print(data)content=data['data']['rankings']#從數據里提取需要的字段ulist=[]foriinrange(num):index=content[i]['rankOverall']#排名name=content[i]['univNameCn']#大學名稱score=content[i]['score']#總分category=content[i]['univCategory']#大學類別ulist.append([index,name,score,category])returnulist#打印提取出的表格信息defprintUnivList(ulist,num):tplt="{0:^10}\t{1:{3}^10}\t{2:^10}\t{4:^10}"print(tplt.format("排名","學校","總分",chr(12288),"類型"))#chr(12288)為空格foriinrange(num):u=ulist[i]print(tplt.format(u[0],u[1],u[2],chr(12288),u[3]))defsearchUnivName(ulist):univName=input("請輸入查找的大學名稱:")flag=1forchinulist:ifunivName==ch[1]:tplt="{0:^10}\t{1:{3}^10}\t{2:^10}\t{4:^10}"print(tplt.format("排名","學校","總分",chr(12288),"類型"))#chr(12288)為空格print(tplt.format(ch[0],ch[1],ch[2],chr(12288),ch[3]))#主程序defmain():num=10url=r"/api/pub/v1/bcur?bcur_type=11&year=2021"text=getHtmlText(url)ulist=fillUnivList(text,580)printUnivList(ulist,num)flag=input("您需要按大學名稱查詢嗎?(Y,N):\n")ifflag.upper()=="Y":searchUnivName(ulist)else:print("程序結束!")main()第十二章【參考答案】一、選擇題1.A2.C3.B4.C5.A6.B7.B8.D9.C10.A二、填空題1.游戲開發2.網絡爬蟲3.WEB開發4.機器學習5.網絡爬蟲編程【或】網絡爬蟲6.圖像處理7.數據分析【或】科學計算8.數據可視化9.HTML解析【或】文本處理10.圖形用戶界面三、編程題1.參考代碼:1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374#繪制佳木斯大學校徽importturtleastt.pensize(5)t.pencolor('green')#繪制菱形t.penup()t.forward(-100)t.pendown()t.right(40)t.fd(200)t.left(80)t.fd(200)t.left(100)t.fd(200)t.left(80)t.fd(200)#繪制內三校合一的塔t.pensize(7)t.penup()t.home()t.fd(53)t.left(90)t.fd(100)t.left(180)t.pendown()t.fd(30)t.right(65)t.fd(30)t.left(63)t.fd(30)t.right(60)t.fd(30)t.penup()t.home()t.fd(53)t.left(90)t.fd(100)t.right(180)t.pendown()t.fd(30)t.left(65)t.fd(30)t.right(63)t.fd(30)t.left(60)t.fd(30)t.p
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 商業智能與教育投資決策風險與回報的分析
- 在線平臺優化下學生的跨領域互動探索
- 智能教育技術如何優化課堂互動
- 學生大腦的記憶系統研究
- 教育無界開啟知識共享新紀元
- 醫療健康數據與教育大數據的整合中的隱私保護
- 2024年咸陽興平市特崗教師招聘筆試真題
- 團隊合作內培訓課件
- 一年級數學計算題專項練習匯編
- 2024-2025學年度重慶青年職業技術學院單招《物理》能力檢測試卷及答案詳解(典優)
- 寶媽日常心理護理
- 2025年社會學概論測試題含答案(附解析)
- 電機學II知到智慧樹章節測試課后答案2024年秋廣東工業大學
- JT-T-1178.2-2019營運貨車安全技術條件第2部分:牽引車輛與掛車
- 美術學院 本科培養方案 - 清華大學 - Tsinghua University
- 項目延期申請表(樣本)
- 《中國腦卒中護理指導規范(2021年版)》課件
- 入團志愿書(2016版本)(可編輯打印標準A4) (1)
- 三基訓練習題集-風濕免疫科(題目及答案)
- 無損檢測射線常見缺陷圖集
- 冷卻塔填料施工組織設計方案和安全措施
評論
0/150
提交評論