資源簡介 中小學教育資源及組卷應用平臺第二單元單元練習及參考答案1.設有一個正整數序列組成的有序表(按遞增次序有序,且允許有相等的整數存在),請編寫能實現下列功能的程序:(1)確定在序列中比正整數x大的數有幾個(相同的數只計算一次,如序列{20,20,17,16,15,15,11,10,8,7,7,5,4}中比10大的數有5個);(2)將比正整數x小的數按遞減次序排列;(3)將比正整數x大的偶數刪除。(4)比較使用數組和鏈表實現上述功能的優劣。2.把二次多項式ax2+bx+c設計成一種抽象數據類型,該類型的數據對象為三個系數項a,b和c,操作部分為:(1)初始化a,b和c的值;(2)做兩個多項式加法;(3)根據給定x的值計算多項式的值;(4)計算方程ax2+bx+c=0的兩個實數根;(5)按照ax2+bx+c的格式輸出二次多項式。3.某航空公司有一個自動預訂飛機票的系統,假設該系統中有一張用單鏈表表示的乘客表,見表2-7。表中結點按乘客姓氏的字母次序進行鏈接(指針暫用序號表示),請為該系統編寫有新乘客訂票時修改乘客表的程序。表2-7乘客表datalinkLiu7Chen4Wang5Bao2Mai8Dong6Xi0Deng5Chang34.約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n個人(以編號1,2,3,…,n分別表示)圍坐在一張圓桌周圍。編號為k的人從1開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個出列;依此規律重復下去,直到圓桌周圍的人全部出列。請用單鏈表設計一個程序求出出列順序(單鏈表最后一個結點的指針指向鏈表的首結點)。參考答案1.importrandomclassSeqList(object):def_init_(self,max=100):self.max=max#默認順序表最多容納10個元素#初始化順序表數組self.num=0self.data[None]self.maxdefis_empty(self):#判定線性表是否為空returnself.numis0defis_full(self)):#判定線性表是否全滿returnself.numisself.max#統計線性表中元素的個數defCount(self):returnself.num#表末尾插入操作defappendLast(self,value):ifself.num>=self.max:print(‘Thelistisfull')returnelse:self.data[self.num]=valueself.num+=1#表任意位置插入操作:definsert(self,i,value):ifnotisinstance(i,int):raiseTypeErrorifi<0andiself.num:raiseIndexErrorforjinrange(self.num,i-1,-1):self.data[j]=self.data[i-1]selfdata[i]=valueself.num+=1#對數據進行排序defsortlist(self):i=0j=0temp=0foriinrange(selfnum-1):forjinrange(i+1,self.num):if(self.data[j]temp=self.data[i]self.data[i]=self.data[j]Self.data[j]=temp#找比key大的,不重復的數據defcompareList(self,key):t=0if(self.data[0]>key)t=t+1Print(self.data[0])foriinrange(1,self.num-1):if(self.data[i]>keyandself.data[i]!=self.data(i-1]):t=t+1Print(self.data[i])Print(“一共有”,t,”個”)#小于key的數據遞減排列defdijian(self,key):t=0foriinrange(0,self.num):if(self.data[i]t=t+1t=t-1K=int(t/2)temp=0#print(“------------k,t------------”,k,t)foriinrange(0,k):temp=self.data[i]self.data[i]=self.data[t]sel.data[t]=tempt=t-1#刪除某一位置的操作defremove(self,i):ifnotisinstance(i,int):raiseTypeErrorifi<0andi>=self.num:raiseIndexErrorforjinrange(i,self.num-1):#此處是self.num-1,因為循環中是j+1#print(j,selfdata[j],self.data[j+1])self.data[j]=self.data[j+1])self.num-=1defdelete(self,index):foriinrange(index,self.num-1):self.data[i]=self.data[i+1]self.num-=1#刪除key之后的偶數defdeleteKey(self,key):i=0while(iif(self.data[i]>keyandself.data(i)%2==0):self.delete(i)else:i+=1#輸出操作defprintlist(self):foriinrange(0,self.num):print(selfdata[i])#print()Print(“----------------------------”)#銷毀操作defdestroy(self):self._init_()seq=SeqList(20)foriinrange(10):#創建10個隨機數的數據t=random.randint(1,100)#print(t)seq.appendLast(t)#print("")Seq.appendLast(seq.data[0])Seq.appendLast(seq.data[1])Seq.appendLast(seq.data[2])Seq.appendLast(seq.data[3])Seq.appendLast(seq.data[2])Seq.appendLast(seq.data[2])#seq.printList()#輸出排序前的數據seq.sortList()#對數據進行排序seq.printList()#出排序后的數據x=int(input("請輸入要比較的數字:"))seq.compareList(x)#和x比較,統計比x大的數據個數print(“將比x小的數按遞減次序排列:")seq.printList()print("將比x大的偶數刪除:")seq.deleteKey(x)#刪除比x大的偶數seq.printList()2.把二次多項式ax2+bx+c設計成一種抽象數據類型,類型的數據對象為三個系數項a,b和c,操作部分為:?初始化a,b和c的值;?做兩個多項式加法;?根據給定x的值計算多項式的值;?計算方程ax2+bx+c=0的兩個實數根;?按照ax2+bx+c的格式輸出二次多項式。參考答案:先創建鏈表,命名為NodeList.py,程序在第3題也需要使用#NodeList.pyclassNode:,,,data:結點保存的數據_next:保存下一個結點對象,,,def_init_(self,data,pnext=None):self.data=dataself.Next=pnextdef_repr_(self):returnstr(self.data)classNodeList:,,,head:頭結點Length:鏈表長度,,,def_init_(self):self.head=Nineself.length=0#判斷鏈表是否為空defisEmpty(self):return(self.length==0)#最后一位添加元素defappend(self,dataOrNode):item=Nodeifisinstance(dataOrNode,Node):item=dataOrNodeelse:item=Node(dataOrNode)ifnotself.head:self.head=itemself.length+=1else:node=self.headwhilenode._nextNode=node._nextnode._next=itemself.length+=1#刪除元素defdelete(self,index):ifself.isEmpty():print("ERROR:NODELISTEMPTY")returnifindex<0orindex>selflength:print(“error:outofindex")returnifindex==0:self.head=self.head._nextself.length-=1returnj=0Node=self.headprev=self.headwhilenode._nextandj<index:prev=nodenode=node._nextself.length-=1#更新元素defupdate(self,index,data):ifself.isEmpty()orindex<0orindex>self.length:print(‘ERROR:OUTOFINDEX’)returnj=0Node=self.headwhilenode._nextandj<index:node=node._nextj+=1ifj==index:node.data=data#獲取元素defgetltem(self,index):ifself.isEmpty()orindex<0orindex>=self.length:print("ERROR:OUTOFINDEX”)returnj=0node=self.headwhilenode._nextandj<index:node=node._nextj+=1returnnode.data#找到特定元素的位置defgetIndex(self,data):j=0ifself.isEmpty():print("ERROR:NODELISTEMPTY")returnnode=self.headwhilenode:ifnode.data=data:returnjnode=node._nextj+=1ifj==self.length:print("%snotfound"%str(data))return#在index的位置插入元素definsert(self,index,dataOrNode):ifself.isEmpty():print("ERROR:NODELISTEMPTY")returnifindex<0orindex>selflength:print("ERROR:OUTOFINDEX”)returnitem=NodeIfisintance(dataOrNode,Node):item=Node(dataOrNode)ifindex==0:item._next=self.headself.head=itemself.length+=1returnj=0node=self.headprev=self.headwhilenode._nextandj<index:prev=nodenode=node._nextj+=1ifj==index:item._next=nodeprev._next=itemself.length+=1#清空defclear(self):self.head=Noneself.length=0def_repr_(self):ifselfisEmpty()print("ERROR:NODELISTEMPTY")returnnode=self.headnlist=””whilenodenlist+=str(node.data)+”“node=node._nextreturnnlistdef_getitem_(self,ind):ifself.isEmpy()orind<0orind>=self.length:print("ERROR:OUTOFINDEX")returnreturnself.getltem(ind)def_setitem_(self,ind,val):ifself.isEmpty()orind<0orind>=self.length:print("ERROR:OUTOFINDEX")returnself.update(ind,val)def_len_(self):returnself.length#------------------------------以下是二次多項式的運算-------------------------------------importNodelistclassFomula:,,,a,b,c方程系數,,,#initdef_init_(self,a,b,c):nodeA=NodeList.Node(a)nodeB=Nodelist.Node(b)nodeC=NodeList.Node(c)nodeList=Nodelist.NodeList()nodeList.append(nodeA)nodeList.append(nodeB)nodeListappend(nodeC)Self.nodeList=nodeList#adddefadd(self,fomula2):f1=self.nodelist.headf2=fomula2.nodeList.headwhile(f1!=None)f1.data+=f2.dataf1=f1.nextf2=f2.next#calculatethesumdefcalValue(self,x):value=0ratio=2f=self.nodelist.headwhile(f!=None):value+=f.data(xratio)f=f._nextratio-=1returnvalue#calculateresultdefcalResult(self):f=self.nodeList.headlist=[]while(f!=None):listappend(f.data)f=f._nexttemp=list[1]2-4list[0]list[2]iftemp<0return”ERROR:NOANSWER”eliftemp==0return-list[1]/(2list[0])else:return[(-list[1]+temp0.5)/2/list[0],(-list[1]-temp0.5)/2/list[0]]#Demonstrationdefshow(self):f=self.nodelist.headlist=[]while(f!=None):list.append(fdata)f=f._nextreturnstr(list[0]+”x2+”+str(list[1]+”x+”+str(list[2])If_name_==”_main_”:print(fomula.Show())print(fomula.calResult())print(fomula.calValue(2))fomulaNew=fomula(2,4,0)fomula.add(fomulaNew)print(fomulashow())print(fomula.calResult())print(fomula.calRValue(2))3.某航空公司有一個自動預訂飛機票的系統,假設該系統中有一張用單鏈表表示的乘客表,如下表所示。表中結點按乘客姓氏的字母次序進行鏈接(指針暫用序號表示),請為該系統編寫有新乘客訂票時修改乘客表的程序。datalinkLiu7Chen4Wang5Bao2Mai8Dong6Xi0Deng5Chang3參考答案:#本題需要用到第二題鏈表的創建Nodelist.pyimportNodeListnodelist=Nodelist,Nodelist()definsert(curString):ifnodeList.isEmptyo():nodeList.append(curString)else:head=nodeList.headposition=0While(head!=None):if(curString>head.data):head=head.nextPosition+=1else:nodeList.insert(position,curString)breakif(head==None):nodeList.append(curString)definit():initialSet=["Liu","Chen","Wang","Bao","Mai","Dong","Xi","Deng",”Chang”]foriinrange(initialSet._len_()):insert(initialSet[i])If_name_==”_main_”:init()headnodeList.headwhile(head!=None):print(head.data)head=head.next1s=input("輸入姓名(輸入#結束):\n”)while(Is!=‘#’):try:Insert(1s)Head=nodelist.headwhile(head!=None):print(head.data)head!=head._next1s=input("輸入姓名(輸入#結束):\n”)exceptExceptionase:Print(e)break4.約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n個人(以編號1,2,3分別表示)圍坐在一張圓桌周圍。編號為k的人從1開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人出列;依此規律重復下去,直到圓桌周圍的人全部出列。請用單鏈表設計一個程序求出出列順序(單鏈表最后一個結點的指針指向鏈表的首結點)。classNode():#定義結點def_init_(self,value,next=None):self.value=valueself.next=nextdefcreateLink(n):#創建鏈表ifn<=0:returnFalseifn==1:returnNode(1)else:root=Node(1)tmp=rootforiinrange(2,n+1):tmp.next=Node(i)tmp=tmp.nexttmp.next=rootreturnrootdefshowLink(root):#打印鏈表tmp=rootwhileTrue:Print(rmp.value)tmp=tmp.nextiftmp==Noneortmp==root:breakdefjosephus(n,k,p):#具體的出圈ifk==1:print(‘最后出列’,n)returnroot=createLink(n)tmp=rootpT=1while(pT<p):tmp=tmp.nextpT+=1whileTrue:foriinrange(k-2):tmp=tmp.nextprint(‘出列:’,tmp.next.value)tmp.next=tmp.next.nexttmp=tmp.nextiftmp.ext=tmp:breakprint(‘最后出列:’,tmp.value)If_name_==”_main_”:n=int(input(“請輸入總人數:"))m=int(input("請輸入m:”))p=int(input("請輸入開始的位置p:"))Josephus(n,m,p)Print(‘------------------------’)21世紀教育網www.21cnjy.com精品試卷·第2頁(共2頁)HYPERLINK"http://21世紀教育網(www.21cnjy.com)"21世紀教育網(www.21cnjy.com) 展開更多...... 收起↑ 資源預覽 縮略圖、資源來源于二一教育資源庫